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

2024-09-23 14:28:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在python中动态生成组合,我有一个varsessionperweeks(介于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])

等等


Tags: inforif动态rangeappendcombinssessionperweeks
1条回答
网友
1楼 · 发布于 2024-09-23 14:28:42

现在,使用combinationsfrom itertools从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)

使用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)]

运行示例:

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)]

相关问题 更多 >