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

ssi*_*i38 14 python list

我有一个.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
Run Code Online (Sandbox Code Playgroud)

现在另一个.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>"
Run Code Online (Sandbox Code Playgroud)

任何人都可以解释为什么我似乎无法扭转名单,无论我做什么?

jon*_*tar 30

正如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]
Run Code Online (Sandbox Code Playgroud)


jco*_*ctx 9

list.reverse()就地反转并且不返回任何内容(None).所以你不要说:


mylist = mylist.reverse()
Run Code Online (Sandbox Code Playgroud)

你说:


mylist.reverse()
Run Code Online (Sandbox Code Playgroud)

或者:


mylist = list(reversed(mylist))
Run Code Online (Sandbox Code Playgroud)


mar*_*eau 5

reverse() list方法对列表进行了排序并返回None以提醒您(根据文档中的注释7 ).内置reversed()函数返回一个迭代器对象,可以将它转换为一个list对象,方法是将它传递给list()构造函数,如下所示:list(reversed(qSort)).你可以通过创建一个长为负值的切片来完成同样的事情,这样它就会倒退,即qSort[::-1].

BTW,list也有一种sort()方法(但要小心,它也会返回None;-).