我有两个列表,如:
list1 = ['square','circle','triangle']
list2 = ['red','green']
如何创建这些列表的所有排列,如下所示:
[
'squarered', 'squaregreen',
'redsquare', 'greensquare',
'circlered', 'circlegreen',
'redcircle', 'greencircle',
'trianglered', 'trianglegreen',
'redtriangle', 'greentriangle'
]
我可以使用itertools
吗?
答案 0 :(得分:61)
您需要 itertools.product
方法,该方法会为您提供两个列表的 Cartesian product 。
>>> import itertools
>>> a = ['foo', 'bar', 'baz']
>>> b = ['x', 'y', 'z', 'w']
>>> for r in itertools.product(a, b): print r[0] + r[1]
foox
fooy
fooz
foow
barx
bary
barz
barw
bazx
bazy
bazz
bazw
您的示例要求提供双向产品(也就是说,您需要'xfoo'以及'foox')。要做到这一点,只需做另一个产品并将结果链接起来:
>>> for r in itertools.chain(itertools.product(a, b), itertools.product(b, a)):
... print r[0] + r[1]
答案 1 :(得分:30)
>>> import itertools
>>> map(''.join, itertools.chain(itertools.product(list1, list2), itertools.product(list2, list1)))
['squarered', 'squaregreen', 'circlered',
'circlegreen', 'trianglered', 'trianglegreen',
'redsquare', 'redcircle', 'redtriangle', 'greensquare',
'greencircle', 'greentriangle']
答案 2 :(得分:12)
怎么样
[x + y for x in list1 for y in list2] + [y + x for x in list1 for y in list2]
IPython交互示例:
In [3]: list1 = ['square', 'circle', 'triangle']
In [4]: list2 = ['red', 'green']
In [5]: [x + y for x in list1 for y in list2] + [y + x for x in list1 for y in list2]
Out[5]:
['squarered',
'squaregreen',
'circlered',
'circlegreen',
'trianglered',
'trianglegreen',
'redsquare',
'greensquare',
'redcircle',
'greencircle',
'redtriangle',
'greentriangle']
答案 3 :(得分:8)
我认为你要找的是两个列表的产物,而不是排列:
#!/usr/bin/env python
import itertools
list1=['square','circle','triangle']
list2=['red','green']
for shape,color in itertools.product(list1,list2):
print(shape+color)
产量
squarered
squaregreen
circlered
circlegreen
trianglered
trianglegreen
如果您同时使用squarered
和redsquare
,那么您可以执行以下操作:
for pair in itertools.product(list1,list2):
for a,b in itertools.permutations(pair,2):
print(a+b)
或者,将其列入一个列表:
l=[a+b for pair in itertools.product(list1,list2)
for a,b in itertools.permutations(pair,2)]
print(l)
产量
['squarered', 'redsquare', 'squaregreen', 'greensquare', 'circlered', 'redcircle', 'circlegreen', 'greencircle', 'trianglered', 'redtriangle', 'trianglegreen', 'greentriangle']
答案 4 :(得分:1)
您可以在任何情况下执行以下操作:
perms = []
for shape in list1:
for color in list2:
perms.append(shape+color)