-1

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

例子:

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

4 回答 4

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']
于 2012-12-05T17:45:18.573 回答
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()而不是简单的串联。

于 2012-12-05T17:44:21.490 回答
0

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

import itertools
result = itertools.product(list1, list2)
于 2012-12-05T17:45:47.077 回答
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)
于 2012-12-05T18:23:29.520 回答