Python中两个列表的排列组合

61 投票
6 回答
81456 浏览
提问于 2025-04-15 17:18

我有两个列表,像这样:

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

我该如何生成这些列表的所有排列组合,比如这样:

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

我可以用 itertools 来实现吗?

6 个回答

18

怎么样呢

[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']
113

你需要使用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

你的例子中提到的是双向的组合(也就是说,你想要'xfoo'和'foox'这两种情况)。要实现这个,只需要再做一次组合,然后把结果连接起来就可以了:

>>> for r in itertools.chain(itertools.product(a, b), itertools.product(b, a)):
...   print r[0] + r[1]
46

在编程中,有时候我们会遇到一些问题,特别是在使用某些工具或库的时候。比如,有人可能在使用某个库时,发现它的某些功能不太好用,或者出现了错误。这时候,我们就需要去查找解决方案,看看有没有其他人遇到过类似的问题。

通常,我们可以在网上找到很多资源,比如论坛、文档或者问答网站(像StackOverflow)。这些地方有很多经验丰富的程序员分享他们的经验和解决方案。

如果你在使用某个工具时遇到问题,首先可以尝试搜索一下相关的关键词,看看有没有人提过类似的问题。很多时候,别人已经找到了解决办法,你只需要按照他们的步骤去做就可以了。

记住,编程是一个不断学习的过程,遇到问题是很正常的。多去查找资料,向别人请教,慢慢你就会变得越来越熟练。

>>> 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']

撰写回答