Python 排序函数sorted

Python 排序函数sorted

函数原型sorted(iterable, key=None, reverse=False)
* iterable 是待排序的数据结构
* key 元素评价函数 用来评价元素大小
* reverse 是否倒序
* 返回值是排好序的数据结构,不改变源数据结构

简单列表结构

a = [9, 8, 6, 3, 2, 1]
result = sorted(a,reverse=True)
print(result) #[9, 8, 6, 3, 2, 1]

复杂列表结构

a = [(1,9),(2,8),(3,7),(4,6),(5,0)]
result = sorted(a,key=lambda x:x[0])#评价函数返回元素第一个值,元素大小按第一个值算
print(result)#[(1, 9), (2, 8), (3, 7), (4, 6), (5, 0)]

猜你喜欢

转载自blog.csdn.net/a540366413/article/details/70859354