gpt4 book ai didi

python - python中两个列表的排列

转载 作者:IT老高 更新时间:2023-10-28 22:12:52 25 4
gpt4 key购买 nike

我有两个列表,例如:

list1 = ['square','circle','triangle']
list2 = ['red','green']

如何创建这些列表的所有排列,如下所示:

[
'squarered', 'squaregreen',
'redsquare', 'greensquare',
'circlered', 'circlegreen',
'redcircle', 'greencircle',
'trianglered', 'trianglegreen',
'redtriangle', 'greentriangle'
]

我可以为此使用 itertools 吗?

最佳答案

你想要 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]

关于python - python中两个列表的排列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1953194/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com