sort是应用在list上的方法,sorted应用于所有可迭代对象。
sort是将原有的列表直接排序,无返回值;sorted是将列表排序后返回一个新的列表,原列表不变。
实例:
C:\Users\Administrator>python
Python 3.6.6 (v3.6.6:4cf1f54eb7, Jun 27 2018, 03:37:03) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>> a = [5,3,6,7,9,3,4,6,7,2,3,1]
>>> a.sort()
>>> a
[1, 2, 3, 3, 3, 4, 5, 6, 6, 7, 7, 9]
>>> a = [5,3,6,7,9,3,4,6,7,2,3,1]
>>> sorted(a)
[1, 2, 3, 3, 3, 4, 5, 6, 6, 7, 7, 9]
>>> b = sorted(a)
>>> b
[1, 2, 3, 3, 3, 4, 5, 6, 6, 7, 7, 9]
>>> a
[5, 3, 6, 7, 9, 3, 4, 6, 7, 2, 3, 1]