2012-12-05 174 views
-1

我需要連接列表中的項目和另一個列表中的項目。在我的情況下,該項目是一個字符串(更準確地說是一個路徑)。連接後,我想獲得一個列表,其中包含所有可能的連接項。Python - 連接列表中的項目和另一個列表中的項目

例子:

list1 = ['Library/FolderA/', 'Library/FolderB/', 'Library/FolderC/'] 

list2 = ['FileA', 'FileB'] 

我想獲得像這樣的列表:

[ 
    'Library/FolderA/FileA', 
    'Library/FolderA/FileB', 
    'Library/FolderB/FileA', 
    'Library/FolderB/FileB', 
    'Library/FolderC/FileA', 
    'Library/FolderC/FileB' 
] 

謝謝!

回答

1

您可以使用列表理解:

>>> [d + f for d in list1 for f in list2] 
['Library/FolderA/FileA', 'Library/FolderA/FileB', 'Library/FolderB/FileA', 'Library/FolderB/FileB', 'Library/FolderC/FileA', 'Library/FolderC/FileB'] 

您可能需要使用os.path.join(),而不是簡單的串聯,雖然。

5
In [11]: [d+f for (d,f) in itertools.product(list1, list2)] 
Out[11]: 
['Library/FolderA/FileA', 
'Library/FolderA/FileB', 
'Library/FolderB/FileA', 
'Library/FolderB/FileB', 
'Library/FolderC/FileA', 
'Library/FolderC/FileB'] 

,或者稍微更便攜(或許魯棒):

In [16]: [os.path.join(*p) for p in itertools.product(list1, list2)] 
Out[16]: 
['Library/FolderA/FileA', 
'Library/FolderA/FileB', 
'Library/FolderB/FileA', 
'Library/FolderB/FileB', 
'Library/FolderC/FileA', 
'Library/FolderC/FileB'] 
+0

這可能是最好使用'os.path.join()'這裏。 –

+0

@Lattyware:已經完成:) – NPE

0

內置itertools模塊定義了一個product()函數爲這樣:

import itertools 
result = itertools.product(list1, list2) 
0

for環可以做這很容易:

my_list, combo = [], '' 
list1 = ['Library/FolderA/', 'Library/FolderB/', 'Library/FolderC/'] 
list2 = ['FileA', 'FileB'] 
for x in list1: 
    for y in list2: 
     combo = x + y 
     my_list.append(combo) 
return my_list 

你也可以打印出來:

list1 = ['Library/FolderA/', 'Library/FolderB/', 'Library/FolderC/'] 
list2 = ['FileA', 'FileB'] 
for x in list1: 
    for y in list2: 
     print str(x + y) 
相關問題