Python排序列表的一部分

时间:2016-02-19 23:04:57

标签: python list python-2.7 sorting

当我使用sort函数对列表的末尾进行排序时,此代码用于查找整数列表的下一个排列并未给出正确的答案。但如果我使用排序函数,它给了我正确的答案。为什么会这样?请有人帮我解决这个问题。

def nextPermutation(self, A):
    n = len(A)
    if n == 1:
        return A
    i = n - 2
    m = A[n - 1]
    while i >= 0:
        if A[i] < m:
            j = i + 1
            while j < len(A) and A[i] < A[j]:
                j += 1
            A[i], A[j - 1] = A[j - 1], A[i]
            A[i + 1 :].sort()  #Here if I use sorted it gives the correct answer
            return A
        else:
            m = max(A[i], m)
        i -= 1
    A.sort()
    return A

2 个答案:

答案 0 :(得分:0)

切片会创建列表的副本。当您说A[i + 1:].sort()时,您正在创建一些A内容的副本,然后对其进行排序。它不会影响A。试试这个:

B = A[i + 1:]
B.sort()
return B

当然,使用sorted()return sorted(A[i + 1:])会更容易,但是根据您的问题,我认为由于某些原因您并不感兴趣。

答案 1 :(得分:0)

嗯,在A[i+1:].sort()行中,A[i+1:]部分创建了一个列表对象。然后,.sort()部分对该列表进行排序。然后,抛弃此 new 对象而不分配任何内容。因此,该行对您的代码没有影响。

我不确定你为什么要经历所有这些麻烦,但是把这个课程编写得更容易:

from itertools import permutations

class PermutationList:
    def __init__(self, pool):
        self.pool = pool
        self._generator = permutations(self.pool)

    def __iter__(self):
        while True:
            try:
                yield list(next(self._generator))
            except StopIteration:
                self._generator = permutations(self.pool)
                raise StopIteration

test_list = PermutationList([1,2,3,4])

for perm in test_list:
    print perm

# Output
# [1, 2, 3, 4]
# [1, 2, 4, 3]
# [1, 3, 2, 4]
# ...
# [4, 3, 2, 1]