先看最简单的情况,若有赵钱孙李周5人需要排班,一人一天,情况如下:
from itertools import permutations for p in permutations('赵钱孙李周'): #全排列 print(''.join(p))
此时会打印出 '赵钱孙李周' 5人的所有情况。现在假如第一天的人必须是周,则需要加上判断即可:
from itertools import permutations for p in permutations('赵钱孙李周'): k = ''.join(p) if k[0] == "周": print(k)
还可以有更加复杂的条件,比如第一天必须赵,第四天必须李
from itertools import permutations for p in permutations('赵钱孙李周'): k = ''.join(p) if k[0] == "赵" and k[3] == "李" : print(k)
结果:
现实中的情况往往更加复杂,比如5人需要分在10天排班,1人2天,每人的班不连续,最后一天必须是赵,第一天不能是周,第3天不能是李
from itertools import permutations for p in permutations('赵钱孙李周赵钱孙李周'): k = ''.join(p) if k[0] != "周" and k[-1] == "赵" and k[2] != "李" and all(k[i] != k[i+1] for i in range(len(k) - 1)): #第一天不能是周,最后一天必须是赵,第3天不能是李,每人的班不连续
print(k)
部分结果:标签:李周,join,Python,import,permutations,赵钱孙,排班,print,排列组合 From: https://www.cnblogs.com/shan-gui-yao/p/18249216