2012-11-02 24 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'] 
相關問題