Skip to main content
 首页 » 编程设计

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

2025年05月04日16over140

我有一个像 [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)]