获取列表中的所有组合

时间:2015-08-28 17:56:28

标签: python

假设我有一个列表[1,1,1,1]。

我希望迭代所有可能的组合,而列表的每个索引都必须包含从1到n的数字。

换句话说,我想制作一个将遍历所有组合的for循环。

如:[n-35,n-5,1,n],[1,1,1,n],[n,1,n,n-19]。我希望你明白这一点。

有没有人知道如何做到这一点?

1 个答案:

答案 0 :(得分:1)

itertools.combinations_with_replacement。应该这样做。

for comb in itertools.combinations_with_replacement(range(1,n+1), 4):
    # comb is (1,1,1,1), then (1,1,1,2), then ...
相关问题