python高级函数 sorted

一、sorted

sorted函数可以用来对列表等进行排序。

sorted函数的函数原型为:sorted(iterable, /, *, key=None, reverse=False)

第一个参数是一个可迭代的对象,一般是一个列表

参数 key是一个函数,这个函数以 iterable中的元素作为参数,返回一个排序用的关键字。

如果传递了这个参数,排序时将会根据这个函数的返回结果来对 iterable 里的元素进行排序,在iterable 里的元素是其他对象或 iterable 多重嵌套时可以很方便地通过 key返回一个排序关键字。

reverse表示排序地方向,当 reverse为 False 时按关键字升序排列,为 True 时按关键字降序排列。

我们来看一个例子:

#示例1
l_1 = [2, 234, 565, 546, 2, 34, 5, 546, 1, 245, 5]
print(sorted(l_1))
#[1, 2, 2, 5, 5, 34, 234, 245, 546, 546, 565]
print(sorted(l_1, reverse=True))
#[565, 546, 546, 245, 234, 34, 5, 5, 2, 2, 1]

#示例2
l_2 = [
    {'c':1},
    {'a':3},
    {'d':2},
    {'b':4}
]
#1 按照字典的键升序排列
print(sorted(l_2, key=lambda item: tuple(item.keys())[0]))
#[{'a': 3}, {'b': 4}, {'c': 1}, {'d': 2}]
#2 按照字典的值升序排列
print(sorted(l_2, key=lambda item: tuple(item.items())[0][1]))
#[{'c': 1}, {'d': 2}, {'a': 3}, {'b': 4}]

猜你喜欢

转载自blog.csdn.net/weixin_34208185/article/details/87430556