当前位置: 移动技术网 > IT编程>脚本编程>Python > Python中List的排序

Python中List的排序

2020年05月01日  | 移动技术网IT编程  | 我要评论

龚伦月,暗色鹦鹉,兰吉春

python对list的排序主要有两种方法:一种是用sorted()函数,这种函数要求用一个变量接收排序的结果,才能实现排序;另一种是用list自带的sort()函数,这种方法不需要用一个变量接收排序的结果.这两种方法的参数都差不多,都有key和reverse两个参数,sorted()多了一个排序对象的参数.

1. list的元素是变量

这种排序比较简单,直接用sorted()或者sort()就行了.

list_sample = [1, 5, 6, 3, 7]
# list_sample = sorted(list_sample)
list_sample.sort(reverse=true)
print(list_sample)

运行结果:

[7, 6, 5, 3, 1]

2. list的元素是tuple

这是需要用key和lambda指明是根据tuple的哪一个元素排序.

list_sample = [('a', 3, 1), ('c', 4, 5), ('e', 5, 6), ('d', 2, 3), ('b', 8, 7)]
# list_sample = sorted(list_sample, key=lambda x: x[2], reverse=true)
list_sample.sort(key=lambda x: x[2], reverse=true)
print(list_sample)

运行结果:

[('b', 8, 7), 
('e', 5, 6),
('c', 4, 5),
('d', 2, 3),
('a', 3, 1)]

3. list的元素是dictionary

这是需要用get()函数指明是根据dictionary的哪一个元素排序.

list_sample = []
list_sample.append({'no': 1, 'name': 'tom', 'age': 21, 'height': 1.75})
list_sample.append({'no': 3, 'name': 'mike', 'age': 18, 'height': 1.78})
list_sample.append({'no': 5, 'name': 'jack', 'age': 19, 'height': 1.71})
list_sample.append({'no': 4, 'name': 'kate', 'age': 23, 'height': 1.65})
list_sample.append({'no': 2, 'name': 'alice', 'age': 20, 'height': 1.62})
list_sample = sorted(list_sample, key=lambda k: (k.get('name')), reverse=true)
# list_sample.sort(key=lambda k: (k.get('name')), reverse=true)
print(list_sample)

运行结果:

[{'no': 1, 'name': 'tom', 'age': 21, 'height': 1.75}, 
{'no': 3, 'name': 'mike', 'age': 18, 'height': 1.78},
{'no': 4, 'name': 'kate', 'age': 23, 'height': 1.65},
{'no': 5, 'name': 'jack', 'age': 19, 'height': 1.71},
{'no': 2, 'name': 'alice', 'age': 20, 'height': 1.62}]

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网