所有我在网上被教导和阅读的都是随机播放和其他方法。我在想是否有另一种简单形式的方法,比如while或for。
如果有人可以帮助我,我是新来的
答案 0 :(得分:2)
你应该看combinations
。
from itertools import combinations
my_list = [1, 2, 3, 4]
list(combinations(my_list, 3))
# [(1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)]
答案 1 :(得分:1)
你所要求的并不完全清楚。如果您只想快速了解列表的排列,请使用itertools.permutations
:
for perm in itertools.permutations(sequence):
# do something with permutation "perm"
如果你想了解如何自己产生排列,那么它会有点复杂。存在多种方式,并且通常选择不同的算法以便以特定顺序产生排列。这是描述in Wikipedia的算法,它以字典顺序生成序列的排列(与itertools
相同):
def permutations(seq):
perm = sorted(seq) # the first permutation is the sequence in sorted order
while True:
yield perm
# find largest index k such that perm[k] < perm[k+1]
for k in range(len(perm)-2, -1, -1):
if perm[k] < perm[k+1]:
break
else: # if none was found, we've already found the last permutation
return
# find the largest index l such that perm[k] < perm[l] (always exists)
for l in range(len(perm)-1, -1, -1):
if p[k] < p[l]:
break
# Build the next permutation. This is equivalent to copying perm,
# swapping the values at indexes `k` and `l`, then reversing the values
# from index `k+1` to the end.
perm = perm[:k]+perm[l:l+1]+perm[-1:l:-1]+perm[k:k+1]+perm[l-1:k:-1]