list.sort() 方法会就地排序列表,也就是说是针对原来的数据进行改变,而不是新建一个列表,然后返回None ,
>>> a = ['action','is','better','than','nothing']
>>> a.sort()
>>> a
['action', 'better', 'is', 'nothing', 'than']
相反的sorted() 则是新建一个列表作为返回值,但是不改变原来的列表。而且这个方法可以接受任何形式的可迭代对象作为参数,甚至包括不可变序列(如元组)或生成器。不管sorted() 接受的是怎样的参数,租后都会返回一个列表。
>>> b=['action','is','better','than','nothing']
>>> sorted(b)
['action', 'better', 'is', 'nothing', 'than']
>>> b
['action', 'is', 'better', 'than', 'nothing']
对于list.sort() 和sorted() 函数都可以接受两个可选的关键字参数。
reverse
若reverse = True , 则以降序输出,默认值为False
>>> a
('b', 'c', 'g', 'd')
>>> sorted(a,reverse = True)
['g', 'd', 'c', 'b']
key
接受用来排序的标准,比如 key = len 将会按照元素的长度来排序,传入key = str.lower 会忽略元素的大小写。
>>> b
['action', 'is', 'better', 'than', 'nothing']
>>> b.sort(key = len)
>>> b
['is', 'than', 'action', 'better', 'nothing']