python中的sort()方法和內建函式sorted()的區別
阿新 • • 發佈:2018-12-13
一,sort()方法 python中 sort()是列表的內建函式,一般不寫引數(取預設值),無返回值,sort()會改變列表,原地排序,因此無需返回值。字典、元組、字串不具有sort()方法,如果呼叫將會返回一個異常。
>>> help(list.sort)
Help on method_descriptor:
sort(...)
L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;
cmp(x, y) -> -1, 0, 1
例如:
>>> a=[1,2,3,9,8,7] >>> a.sort() >>> a [1, 2, 3, 7, 8, 9] >>>
二,sorted()函式 sorted()是python的內建函式,該函式不改變原物件,呼叫時一般只需給出一個引數(引數可以是列表、字典、元組、字串),其餘引數取預設值,無論傳遞什麼引數,都將返回一個以列表為容器的返回值,如果是字典將返回鍵的列表。
>>> b=[1,2,3,9,8,7] >>> c=sorted(b) >>> c [1, 2, 3, 7, 8, 9] >>> >>> b.sorted() Traceback (most recent call last): File "<pyshell#196>", line 1, in <module> b.sorted() AttributeError: 'list' object has no attribute 'sorted' >>>
報錯:列表裡面沒有sorted()屬性