簡體   English   中英

無法反轉 Python 中的列表,將“Nonetype”作為列表

[英]Unable to reverse lists in Python, getting "Nonetype" as 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() function 更改了列表。 它不返回列表,而是改變qSort

如果您想“返回”反向列表,以便可以像您在示例中嘗試的那樣使用它,您可以做一個方向為 -1 的切片

所以用print qSort[::-1]替換print qSort.reverse()


你應該知道切片,它有用的東西。 我真的沒有在教程中看到一個地方一次性描述了所有內容( 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]

list.reverse() 就地反轉並且不返回任何內容(無)。 所以你不要說:


mylist = mylist.reverse()

你說:


mylist.reverse()

或者:


mylist = list(reversed(mylist))

reverse() list方法對列表進行排序並返回None以提醒您這一點(根據文檔中的注釋 7)。 The built-in reversed() function returns an iterator object, which can be turned into a list object by passing it to the list() constructor function like this: list(reversed(qSort)) . 你可以通過創建一個長為負的切片來完成同樣的事情,這樣它就會倒退,即qSort[::-1]

順便說一句, list也有一個sort()方法(但要小心,它也返回None ;-)。

l5= [60,70,77]

myl2 = 列表(反轉(l5))

打印(myl2)

或者

mylist2 =[50,60,80,90]

mylist2.reverse()

打印(mylist2)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM