2012-11-02 30 views
0

可能重复:
All combinations of a list of lists如何在列表中的每个项目与另一个列表的所有值在Python

我一直在试图使用Python字符串添加两列在一起我无法用我试过的for循环的不同安排来工作。我所拥有的是两个列表,我想从另外两个列表中创建第三个列表,以便列表1中的索引[0]将列表2中的所有索引依次添加到列表中(每个列表中都有一个单独的条目列表),然后按[1]从列表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]等等。请帮助!

回答

3

你可以尝试这样的

resultlist=[] 
for i in snipppets1: 
for j in snippets2: 
    resultlist.append(i+j) 
print resultlist 
+1

谢谢。这是我最初想要的,但我一直在搞乱 – spikey273

+0

完全没问题 –

11
import itertools 

snippets1 = ["aka", "btb", "wktl"] 
snippets2 = ["tltd", "rth", "pef"] 

resultlist = [''.join(pair) for pair in itertools.product(snippets1, snippets2)] 
+0

谢谢,这是伟大的 – spikey273

2

而对完整性的考虑,我想我应该指出,不使用itertools一个衬垫(但迭代工具的做法与product应该是首选):

[i+j for i in snippets1 for j in snippets2] 
# ['akatltd', 'akarth', 'akapef', 'btbtltd', 'btbrth', 'btbpef', 'wktltltd', 'wktlrth', 'wktlpef'] 
相关问题