gpt4 book ai didi

python - 如何从允许重复的python列表中获取所有可能的组合

转载 作者:太空宇宙 更新时间:2023-11-04 07:54:32 24 4
gpt4 key购买 nike

我有一个像 [1,2,3] 这样的列表,我想得到以下结果:

1
1,1
1,1,1
1,2
1,2,1
1,2,2
1,2,3
1,2
1,3
1,3,3
2,1,2
2,2,1
3,1,1
etc

我试过使用 itertools,但我只得到没有重复的组合。

有谁知道我怎样才能获得具有所需结果的列表?

最佳答案

您需要 itertools.combinations_with_replacement() 并改变 r。这不在您的订单中,因为不清楚这是否是一项要求,例如:

In []:
from itertools import combinations_with_replacement as cwr
nums = [1, 2, 3]
[x for n in range(1, len(nums)+1) for x in cwr(nums, r=n)]

Out[]:
[(1,), (2,), (3,), (1, 1), (1, 2), (1, 3), (2, 2), (2, 3), (3, 3), (1, 1, 1), (1, 1, 2),
(1, 1, 3), (1, 2, 2), (1, 2, 3), (1, 3, 3), (2, 2, 2), (2, 2, 3), (2, 3, 3), (3, 3, 3)]

In []:
from itertools import product
[x for n in range(1, len(nums)+1) for x in product(nums, repeat=n)]

Out[]:
[(1,), (2,), (3,), (1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3),
(1, 1, 1), (1, 1, 2), (1, 1, 3), (1, 2, 1), (1, 2, 2), (1, 2, 3), (1, 3, 1), (1, 3, 2),
(1, 3, 3), (2, 1, 1), (2, 1, 2), (2, 1, 3), (2, 2, 1), (2, 2, 2), (2, 2, 3), (2, 3, 1),
(2, 3, 2), (2, 3, 3), (3, 1, 1), (3, 1, 2), (3, 1, 3), (3, 2, 1), (3, 2, 2), (3, 2, 3),
(3, 3, 1), (3, 3, 2), (3, 3, 3)]

关于python - 如何从允许重复的python列表中获取所有可能的组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50623552/

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