gpt4 book ai didi

Python 加入每个列表中元素的所有组合

转载 作者:太空狗 更新时间:2023-10-30 02:13:35 24 4
gpt4 key购买 nike

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

谢谢!

最佳答案

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

关于Python 加入每个列表中元素的所有组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7746777/

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