如何在 python 中获取大小为 k 的列表的所有组合(其中 k > 列表的长度)?
How to get all combinations of list of size k (where k > length of the list) in python?
这什么都不打印:
from itertools import combinations
comb = combinations([1,2], 3)
for i in comb:
print(i)
我希望输出为:
(1,2,2) (1,2,1) (1,1,2) (1,1,1) (2,1,2) (2,1,1) (2,2,1) (2,2,2)
您不能从 2 项列表生成 3 元素组合。试试这个:
comb = combinations([1,2]*3, 3)
这基本上将可迭代对象扩展为 6 项列表 ([1, 2, 1, 2, 1, 2]
)。
好像你只想要 product
,而不是 combinations
:
from itertools import product
for i in product([1, 2], repeat=3):
print(i)
combinations
使您获得独特的组合,而无需在任何组合中重复使用元素,这意味着不可能从两个源元素中提取三个元素。它也是 order-insensitive,所以它不会给你 (1, 2)
和 (2, 1)
即使你只要求大小 2
的组合(只有 permutations
会这样做).在您的情况下,您似乎希望通过每个索引循环每个元素,允许重复(combinations
/permutations
不会)和 order-sensitive(combinations_with_replacement
会't do),这样就剩下 product
.
这什么都不打印:
from itertools import combinations
comb = combinations([1,2], 3)
for i in comb:
print(i)
我希望输出为:
(1,2,2) (1,2,1) (1,1,2) (1,1,1) (2,1,2) (2,1,1) (2,2,1) (2,2,2)
您不能从 2 项列表生成 3 元素组合。试试这个:
comb = combinations([1,2]*3, 3)
这基本上将可迭代对象扩展为 6 项列表 ([1, 2, 1, 2, 1, 2]
)。
好像你只想要 product
,而不是 combinations
:
from itertools import product
for i in product([1, 2], repeat=3):
print(i)
combinations
使您获得独特的组合,而无需在任何组合中重复使用元素,这意味着不可能从两个源元素中提取三个元素。它也是 order-insensitive,所以它不会给你 (1, 2)
和 (2, 1)
即使你只要求大小 2
的组合(只有 permutations
会这样做).在您的情况下,您似乎希望通过每个索引循环每个元素,允许重复(combinations
/permutations
不会)和 order-sensitive(combinations_with_replacement
会't do),这样就剩下 product
.