-2

我在网上学习和阅读的只是随机播放和其他方法。我在想是否还有另一种具有简单形式的方法,例如 while 或 for。

如果有人可以帮助我,我是新手

4

2 回答 2

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)]
于 2013-09-12T05:25:58.800 回答
1

目前尚不完全清楚您的要求。如果您只想快速了解列表的排列,请使用itertools.permutations

for perm in itertools.permutations(sequence):
    # do something with permutation "perm"

如果您想了解如何自己产生排列,那就有点复杂了。有多种方法可以走,并且通常选择不同的算法以便以特定顺序产生排列。这是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]
于 2013-09-12T08:14:15.403 回答