转自 https://www.jianshu.com/p/419a8732ac62
一、函数sort()
sort() :仅对list对象进行排序,会改变list自身的顺序,没有返回值,即原地排序;
list.sort(key=None, reverse=False)
- key :设置排序方法,或指定list中用于排序的元素;
- reverse :升降序排列,默认为升序排列;
- 一维元素组成的list排序:忽略参数key
>>> a = ['TaoBao', 'Google', 'BaiDu']
>>> a.sort()
>>> a
['BaiDu', 'Google', 'TaoBao']
- dict组成的list排序
- 参数key获取dict的key或value值进行排序
>>> a = [{'dell': 200}, {'mac': 100}]
# 字典的value排序
>>> a.sort(key=lambda x: list(x.values()))
>>> a
[{'mac': 100}, {'dell': 200}]
# 字典的key排序
>>> a.sort(key=lambda x: list(x.keys()))
>>> a
[{'dell': 200}, {'mac': 100}]