Python连接每个列表内的所有元素组合

4 投票
2 回答
1868 浏览
提问于 2025-04-17 04:12

我有一个包含多个元组的列表,每个元组里有两个元素,比如:[('1','11'),('2','22'),('3','33'),...n]

我想知道怎么能找到每个元组的所有组合,但每次只能选择一个元素。

举个例子,结果可能是这样的:

[[1,2,3],[11,2,3],[11,2,3],[11,22,33],[11,2,33],[11,22,3],[1,22,3],[1,22,33],[1,2,33]]`

使用itertools.combinations可以得到所有组合,但它不能保证每次只从每个元组中选择一个元素。

谢谢!

2 个回答

1

你有没有看过 itertools文档

>>> import itertools
>>> l = [('1','11'),('2','22'),('3','33')]
>>> list(itertools.product(*l))
[('1', '2', '3'), ('1', '2', '33'), ('1', '22', '3'), ('1', '22', '33'), ('11', '2', '3'), ('11', '2', '33'), ('11', '22', '3'), ('11', '22', '33')]
7

使用 itertools.product

In [88]: import itertools as it
In [89]: list(it.product(('1','11'),('2','22'),('3','33')))
Out[89]: 
[('1', '2', '3'),
 ('1', '2', '33'),
 ('1', '22', '3'),
 ('1', '22', '33'),
 ('11', '2', '3'),
 ('11', '2', '33'),
 ('11', '22', '3'),
 ('11', '22', '33')]

撰写回答