轻松上手,快乐学习!

Python 列表 sort() 方法


实例

按字母顺序对列表排序:

cars = ['Ford', 'BMW', 'Volvo']

cars.sort()

运行示例»

定义和用法

sort()方法默认对列表进行排序。 可以创建一个函数来确定排序标准。

语法

list.sort(reverse=True|False, key=myFunc)

参数值

参数 描述
reverse 可选。 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)
运行示例»

实例

根据字典的“year”值对字典列表进行排序:
# 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)
运行示例»

实例

按值的长度对列表进行排序反转:
# 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)
运行示例»