我一直在尝试使用python将两个字符串列表添加到一起,我无法使用我尝试过的for循环的不同安排。我有两个列表,我想从其他两个列表中创建第三个列表,因此列表1中的索引[0]依次将列表2中的所有索引添加到它中(每个索引都是新的列表),然后从list1的索引[1]相同,依此类推..
snippets1 = ["aka", "btb", "wktl"]
snippets2 = ["tltd", "rth", "pef"]
resultlist = ["akatltd", "akarth", "akapef", "btbtltd", "btbrth", "btbpef", "wktltltd", "wktlrth", "wktlpef"]
我知道答案很简单,但无论我做什么,我都会得到一些根本不起作用的东西,或者它将snippets1 [0]添加到snippets2 [0],snippets1 [1]到snippets2 [1]和等等。求救!
答案 0 :(得分:11)
import itertools
snippets1 = ["aka", "btb", "wktl"]
snippets2 = ["tltd", "rth", "pef"]
resultlist = [''.join(pair) for pair in itertools.product(snippets1, snippets2)]
答案 1 :(得分:3)
您可以尝试这样
resultlist=[]
for i in snipppets1:
for j in snippets2:
resultlist.append(i+j)
print resultlist
答案 2 :(得分:3)
为了完整起见,我想我应该指出一个班轮没有使用itertools
(但是应该优先选择带product
的itertools方法):
[i+j for i in snippets1 for j in snippets2]
# ['akatltd', 'akarth', 'akapef', 'btbtltd', 'btbrth', 'btbpef', 'wktltltd', 'wktlrth', 'wktlpef']