我有两个列表,如:
list1 = ['square','circle','triangle']
list2 = ['red','green']
Run Code Online (Sandbox Code Playgroud)
如何创建这些列表的所有排列,如下所示:
[
'squarered', 'squaregreen',
'redsquare', 'greensquare',
'circlered', 'circlegreen',
'redcircle', 'greencircle',
'trianglered', 'trianglegreen',
'redtriangle', 'greentriangle'
]
Run Code Online (Sandbox Code Playgroud)
我可以用itertools它吗?
Joh*_*lla 68
你想要这个itertools.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
Run Code Online (Sandbox Code Playgroud)
您的示例要求提供双向产品(即,您需要'xfoo'以及'foox').要做到这一点,只需做另一个产品并链接结果:
>>> for r in itertools.chain(itertools.product(a, b), itertools.product(b, a)):
... print r[0] + r[1]
Run Code Online (Sandbox Code Playgroud)
Nad*_*mli 31
>>> 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']
Run Code Online (Sandbox Code Playgroud)
Mic*_*zyk 12
怎么样
[x + y for x in list1 for y in list2] + [y + x for x in list1 for y in list2]
Run Code Online (Sandbox Code Playgroud)
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']
Run Code Online (Sandbox Code Playgroud)
我认为你要找的是两个列表的产物,而不是排列:
#!/usr/bin/env python
import itertools
list1=['square','circle','triangle']
list2=['red','green']
for shape,color in itertools.product(list1,list2):
print(shape+color)
Run Code Online (Sandbox Code Playgroud)
产量
squarered
squaregreen
circlered
circlegreen
trianglered
trianglegreen
Run Code Online (Sandbox Code Playgroud)
如果你想既squarered和redsquare,那么你可以做这样的事情:
for pair in itertools.product(list1,list2):
for a,b in itertools.permutations(pair,2):
print(a+b)
Run Code Online (Sandbox Code Playgroud)
或者,使其成为一个列表:
l=[a+b for pair in itertools.product(list1,list2)
for a,b in itertools.permutations(pair,2)]
print(l)
Run Code Online (Sandbox Code Playgroud)
产量
['squarered', 'redsquare', 'squaregreen', 'greensquare', 'circlered', 'redcircle', 'circlegreen', 'greencircle', 'trianglered', 'redtriangle', 'trianglegreen', 'greentriangle']
Run Code Online (Sandbox Code Playgroud)
在任何情况下,您都可以执行以下操作:
perms = []
for shape in list1:
for color in list2:
perms.append(shape+color)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
34652 次 |
| 最近记录: |