python - 无法在 Python 中反转列表,获取 "Nonetype"作为列表

标签 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

现在另一个.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]

关于python - 无法在 Python 中反转列表,获取 "Nonetype"作为列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5846004/

相关文章:

python - 关闭文件后如何在内存中保留一个 h5py 组?

python - 在修补导入的模块时模拟返回 ImportError

list - 通过过滤器列表过滤元素列表

list - 在 Scala 2.7.5 中将元素附加到列表的非弃用方法?

python - 属性错误 : 'DataFrame' object has no attribute 'ix'

python - 删除列表中的重复项,同时保持其顺序(Python)

Python - 只打印少于五个字符的单词

C++ 列表实现

ruby-on-rails - ruby rails : re-order checkbox tag

Python 列表 append 问题