Python/ref list sort
来自菜鸟教程
<languages />
Python List sort()方法
例
按字母顺序对列表进行排序:
cars = ['Ford', 'BMW', 'Volvo']
cars.sort()
定义和用法
The
sort()
方法默认对列表进行升序排序。
您还可以使函数决定排序标准。
句法
list.sort(reverse=True|False, key=myFunc)
参数值
| 参数 | 描述 |
|---|---|
| 相反 | 可选的。reverse = True将对列表降序排序。默认为reverse = False |
| key | 可选的。指定排序标准的功能 |
更多例子
例
排序列表降序:
cars = ['Ford', 'BMW', 'Volvo']
cars.sort(reverse=True)
例
按值的长度对列表进行排序:
# A function that returns the length of the value:
def myFunc(e):
return len(e)
cars = ['Ford', 'Mitsubishi', 'BMW', 'VW']
cars.sort(key=myFunc)
例
根据词典的“年”值对词典列表进行排序:
# A function that returns the 'year' value:
def myFunc(e):
return e['year']
cars = [
{'car': 'Ford', 'year': 2005},
{'car': 'Mitsubishi', 'year': 2000},
{'car': 'BMW', 'year': 2019},
{'car': 'VW', 'year': 2011}
]
cars.sort(key=myFunc)
例
按值的长度对列表进行排序 and 逆转:
# A function that returns the length of the value:
def myFunc(e):
return len(e)
cars = ['Ford', 'Mitsubishi', 'BMW', 'VW']
cars.sort(reverse=True, key=myFunc)