我有两个列表,例如:
list1 = ['square','circle','triangle']
list2 = ['red','green']
我如何创建这些列表的所有排列,如下所示:
[
'squarered', 'squaregreen',
'redsquare', 'greensquare',
'circlered', 'circlegreen',
'redcircle', 'greencircle',
'trianglered', 'trianglegreen',
'redtriangle', 'greentriangle'
]
我可以用吗itertools
为了这?
你想要的itertools.product http://docs.python.org/library/itertools.html#itertools.product方法,这会给你笛卡尔积 http://en.wikipedia.org/wiki/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]
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)