1. 程式人生 > >Python中sort()和sorted()的區別

Python中sort()和sorted()的區別

-s 可變對象 傳遞 內置函數 ict pan 16px nbsp lin

1、sort()是可變對象(字典)的方法,無參數無返回值, sort()會改變可變對象,因此無需返回值。例如:

list:

1 >>> a = [4,3,7,8]
2 >>> a.sort()
3 >>> a
4 [3, 4, 7, 8]

即sort()直接將可變對象的值給改變了。

2、sorted()是python的內置函數,並不是可變對象(列表、字典)的特有方法,sorted()函數需要一個參數(參數可以是列表、字典、元組、字符串),無論傳遞什麽參數,都將返回一個以列表為容器的返回值,如果是字典將返回鍵的列表。

list:

1
>>> a = [4,3,7,8] 2 >>> sorted(a) 3 [3, 4, 7, 8] 4 >>> a 5 [4, 3, 7, 8]

即sorted會返會一個list副本,同時將原來list的值改變了可將這個返回的值賦給其他變量。

dict:

1 >>> b = {1:ab,2:degg,4:ght,9:d}
2 >>> sorted(b)
3 [1, 2, 4, 9]
4 >>> b
5 {1: ab, 2: degg, 4: ght, 9: 
d}

即sorted(dict)時,是按key排序,同時將key返回成一個列表。

Python中sort()和sorted()的區別