无法在Python中反转列表,将“ Nonetype”作为列表


问题内容

我有一个.py包含列表的文件,找到最低编号,将其放入新数组,从第一个数组中删除最低编号,然后重复执行,直到原始数组返回不再包含更多项:

def qSort(lsort):
    listlength = len(lsort)
    sortedlist = list()
    if listlength == 0:
        return lsort
    else:
        while listlength > 0:
            lmin = min(lsort)
            sortedlist.append(lmin)
            lsort.remove(lmin)
            listlength = len(lsort)
        return sortedlist

现在,另一个.py文件导入qSort并在某些列表上运行,并将其保存到变量中。然后,我尝试使用.reverse()列表上的命令,最终将其作为NoneType。我尝试使用reversed(),但所做的只是说"<listreverseiterator object at 0xSomeRandomHex>"

from qSort import qSort #refer to my first Pastebin

qSort = qSort([5,42,66,1,24,5234,62])
print qSort #this prints the sorted list
print type(qSort) #this prints <type 'list'>
print qSort.reverse() #this prints None
print reversed(qSort) #this prints "<listreverseiterator object at 0xSomeRandomHex>"

谁能解释为什么无论我做什么我都似乎无法撤消这份清单?


问题答案:

正如jcomeau提到的,该.reverse()函数将列表更改到位。它不返回列表,而是进行qSort更改。

如果要“返回”已反转的列表,因此可以像在示例中尝试的那样使用它,则可以进行方向为-1的切片

因此,更换print qSort.reverse()print qSort[::-1]


您应该了解切片及其有用的内容。我没有真正在本教程中看到一个同时描述了所有内容的地方((http://docs.python.org/tutorial/introduction.html#lists并没有涵盖所有内容),所以希望这里有一些说明性的内容例子。

语法是: a[firstIndexInclusive:endIndexExclusive:Step]

>>> a = range(20)
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
>>> a[7:] #seventh term and forward
[7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
>>> a[:11] #everything before the 11th term
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> a[::2] # even indexed terms.  0th, 2nd, etc
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
>>> a[4:17]
[4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
>>> a[4:17:2]
[4, 6, 8, 10, 12, 14, 16]
>>> a[::-1]
[19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
>>> a[19:4:-5]
[19, 14, 9]
>>> a[1:4] = [100, 200, 300] #you can assign to slices too
>>> a
[0, 100, 200, 300, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]