简体   繁体   English

如何计算 Python 中的组合

[英]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 = 4k = 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.

相关问题 如何在 python/itertools 中计算一级方程式比赛的所有组合 - How to calculate all combinations of a Formula 1 race in python/itertools 如何计算 Python 中 N 个不同词典的所有组合 - How can I calculate all combinations of N different dictionaries in Python 如何计算列表的所有组合 - How to calculate all the combinations of lists 用于从字典计算aded组合的Python脚本 - Python script to calculate aded combinations from a dictionary Python - 计算不同值的组合作为总和 - Python - Calculate combinations of different values as a sum 如何在python中进行组合? - How to make combinations in python? 如何计算组合之间差异最小的所有可能组合 - how to calculate all possible combinations with the lowest diviation between the combinations Python:如何计算给定数字的各个部分的组合,给出数字,列表长度,第一个和最后一个数字 - Python: How to calculate combinations of parts of a given number, giving the number, list lenght, first and last number 如何计算所有可能的列组合的总数 - How to calculate totals of all possible combinations of columns Python Pandas:如何找到组合模式(组合的组合)-时间序列 - Python Pandas: How to find patterns of combinations (Combinations of Combinations) - time series
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM