[英]How to get all possible combinations from a list in python allowing repetition
[英]Finding all combinations of a list in Python with repetition
我正在寻找并打印长度为 5 的集合 (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12) 的所有可能组合。应该有 13 个选择 5组合 (6188) 因为顺序无关紧要,并且允许重复。 我找到了这段代码并正在使用它:
from itertools import product
for item in product([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
repeat=5):
print(item)
但是,这不会打印所有 6188 种组合。 试图弄清楚如何调整代码,使其吐出所有组合。
您想要的是使用combinations_with_replacement
正如@Dani Mesejo 评论的那样。
从文档:
从输入迭代中返回元素的 r 个长度子序列,允许单个元素重复多次。
from itertools import combinations_with_replacement
l = list(combinations_with_replacement([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], 5))
print(len(l)) # 6188
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.