Python|查找字符串和列表的混合组合
有时,在使用Python时,我们可能会遇到需要组合字符串和字符列表的问题。这种类型的问题可能出现在我们需要交错数据的领域。让我们讨论可以执行此任务的某些方式。
方法 #1:使用循环 + enumerate() + replace()
可以使用上述功能的组合来执行此任务。在这里,我们只是迭代字符列表的每个元素并使用暴力方式插入每个组合。
# Python3 code to demonstrate working of
# Mixed Combinations of string and list
# using loop + enumerate() + replace()
# initialize list and string
test_list = ["a", "b", "c"]
test_str = "gfg"
# printing original list and string
print("The original list : " + str(test_list))
print("The original string : " + test_str)
# Mixed Combinations of string and list
# using loop + enumerate() + replace()
res = []
for idx, ele in enumerate(test_str):
res += [test_str[ : idx] + test_str[idx : ].replace(ele, k, 1)
for k in test_list]
# printing result
print("The list after mixed Combinations : " + str(res))
输出 :
The original list : [‘a’, ‘b’, ‘c’]
The original string : gfg
The list after mixed Combinations : [‘afg’, ‘bfg’, ‘cfg’, ‘gag’, ‘gbg’, ‘gcg’, ‘gfa’, ‘gfb’, ‘gfc’]
方法#2:使用列表推导
上述功能可用于执行此任务。在此,我们提供了一种使用理解的单行替代方案。
# Python3 code to demonstrate working of
# Mixed Combinations of string and list
# using list comprehension
# initialize list and string
test_list = ["a", "b", "c"]
test_str = "gfg"
# printing original list and string
print("The original list : " + str(test_list))
print("The original string : " + test_str)
# Mixed Combinations of string and list
# using list comprehension
res = [test_str[ : idx] + ele + test_str[idx + 1 : ]\
for idx in range(len(test_str)) for ele in test_list]
# printing result
print("The list after mixed Combinations : " + str(res))
输出 :
The original list : [‘a’, ‘b’, ‘c’]
The original string : gfg
The list after mixed Combinations : [‘afg’, ‘bfg’, ‘cfg’, ‘gag’, ‘gbg’, ‘gcg’, ‘gfa’, ‘gfb’, ‘gfc’]