简体   繁体   English

如何在 python 中动态生成列表组合

[英]How to generate dynamically combinations of list in python

I want to generate combination dynamically in python, I have a var sessionperweeks (between 2 and 6)我想在 python 中动态生成组合,我有一个 var sessionperweeks (在 2 到 6 之间)

if sessionperweeks==2

    for i in range(0,7):
        for j in range(i+1,7):
            combins.append([i,j])

if sessionperweeks==3

    for i in range(0,7):
        for j in range(i+1,7):
            for k in range(j+1,7):
                combins.append([i,j,k])

and so on等等

Here you go, using combinations from itertools to pick sessions per week from 0-6:这里是 go,使用来自itertoolscombinations从 0-6 每周挑选会话:

from itertools import combinations

sessionsperweek = int(input("Enter sessions per week:"))

combins = list(combinations(range(7), sessionsperweek))
print("Your possible combinations are:")
print(combins)

Example run with 2 (since OP updated):使用 2 运行的示例(因为更新了 OP):

Enter sessions per week:2
Your possible combinations are:
[(0, 1), (0, 2), (0, 3), (0, 4), (0, 5), (0, 6), (1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (2, 3), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6), (4, 5), (4, 6), (5, 6)]

Example run:示例运行:

Enter sessions per week:6
Your possible combinations are:
[(0, 1, 2, 3, 4, 5), (0, 1, 2, 3, 4, 6), (0, 1, 2, 3, 5, 6), (0, 1, 2, 4, 5, 6), (0, 1, 3, 4, 5, 6), (0, 2, 3, 4, 5, 6), (1, 2, 3, 4, 5, 6)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM