[英]How to calculate combinations in Python
I want to calculate a combination set as a collection of all possible subsets of k
items selected from n
items.我想将组合集计算为从
n
个项目中选择的k
个项目的所有可能子集的集合。 For example, if n = 4
and k = 3
, then the items are the integers (0, 1, 2, 3)
, then there are 4
possible combination elements:例如,如果
n = 4
和k = 3
,则项目是整数(0, 1, 2, 3)
,则有4
种可能的组合元素:
[0, 1, 2]
[0, 1, 3]
[0, 2, 3]
[1, 2, 3]
Is there a function to do it in Python?在 Python 中是否有 function 可以做到?
itertools.combinations
produces the desired output: itertools.combinations
生成所需的 output:
from itertools import combinations
n = 4
k = 3
# combinations() outputs tuples.
# Use list() to transform the tuples into lists.
print([list(combination) for combination in combinations(range(n), 3)])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.