Python - 将列表中的项与另一个列表中的项连接起来

时间:2012-12-05 17:41:52

标签: python list

我需要将列表中的项目与另一个列表中的项目连接起来。在我的例子中,该项是一个字符串(更准确的路径)。在连接之后,我想获得一个列表,其中包含由连接产生的所有可能项目。

示例:

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'
]

谢谢!

4 个答案:

答案 0 :(得分: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']

答案 1 :(得分: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()而不是简单连接。

答案 2 :(得分:0)

内置itertools模块为此定义了product()函数:

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

答案 3 :(得分: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)