python的reverse函數(shù)翻轉結果為None的問題
今天刷二級題的時候,遇到一個問題
>>> L2=[1,2,3,4] >>> L3=L2.reverse() >>> print( L3) None >>> print(L3) None >>> print(L2.reverse()) None
其實我想讓它輸出[4,3,2,1]
reverse函數(shù),翻轉列表
然后我改了一下
>>> L2.reverse() >>> L3=L2 >>> print(L3) [4, 3, 2, 1] >>> print(L2) [4, 3, 2, 1] >>>
這是在網(wǎng)上找到的解釋
a=[1,2,3,4].reverse() – why “a” is None?
看到其討論說到:
b = [1,2,3,4] a = b.reverse() would change the value of b.
才想起來,原來這個reverse函數(shù),針對列表的操作,其結果是直接改變列表本身(為了節(jié)省空間),所以,直接就把原先的list改為你所想要的reversed后的結果了,而返回值,是空的,不返回任何值。
所以,本身直接使用:
a.reverse(); # -> is OK, the self is reversed !!!
補充知識:Python中reverse與reverse=true
排序
a = [2, 3, 1] a.sort(reverse=True) print(a) # [3, 2, 1]
沒有排序
a = [2, 3, 1] a.reverse() print(a) # [1, 3, 2]
以上這篇python的reverse函數(shù)翻轉結果為None的問題就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Python?xmltodict實現(xiàn)簡化XML數(shù)據(jù)處理
Python社區(qū)為提供了xmltodict庫,它專為簡化XML與Python數(shù)據(jù)結構的轉換而設計,本文主要來為大家介紹一下如何使用xmltodict實現(xiàn)簡化XML數(shù)據(jù)處理,希望對大家有所幫助2025-01-01

