python排序函数--sorted()

2019-05-22  本文已影响0人  ClementCJ

sorted()函数是python的内置函数,返回的是一个有序的list,定义如下:

sorted(iterable, *, key=None, reverse=False)

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 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)]
上一篇下一篇

猜你喜欢

热点阅读