sorted()函数是python的内置函数,返回的是一个有序的list,定义如下:
sorted(iterable, *, key=None, reverse=False)
- iterable时一个待排序的可迭代对象;
- key是可选参数,指定一个参数的函数,这个函数用于从iterable中的每个元素提取比较直;
key specifies a function of one argument that is used to extract a comparison key from each element in iterable (for example, key=str.lower). The default value is None (compare the elements directly).
- reverse是可选参数,类型是布尔类型,表示是否对排序结果进行翻转。
reverse is a boolean value. If set to True, then the list elements are sorted as if each comparison were reversed.
一个例子:
>>> dt = {'a': 5, 'b':3, 'c':6} #字典
>>> import operator
>>> sorted_dt = sorted(dt.items(), key = operator.itemgetter(1), reverse = True) # operator.itemgetter 获取对象的哪个维度的数据
>>> type(sorted_dt)
<class 'list'>
>>> sorted_dt
[('c', 6), ('a', 5), ('b', 3)]
>>> sorted_dt = sorted(dt.items(), key = operator.itemgetter(0), reverse = True)
>>> sorted_dt
[('c', 6), ('b', 3), ('a', 5)]
网友评论