Python连接每个lis中元素的所有组合

2024-04-27 00:52:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个元组列表,每个元组包含两个元素:[('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.组合提供所有组合,但不保留从每个元组中只选择一个元素。在

谢谢!在


Tags: 元素示例列表元组itertools
2条回答

使用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')]

你读过itertoolsdocumentation吗?在

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

相关问题 更多 >