说明
对List进行排序,Python提供了两个方法: list.sort()
和sorted(list)
- sorted(list)返回一个对象,可以用作表达式。原来的list不变,生成一个新的排好序的list对象。
- list.sort() 不会返回对象,改变原有的list
用List的内建函数list.sort进行排序
sort(self, key=None, reverse=False)
reverse: True 倒叙排序
-
普通数组排序
my_list = [1, 2, 5, 6, 3] my_list.sort() print(my_list) # [1, 2, 3, 5, 6]
-
dict数组排序
my_list = [{'key': 1}, {'key': 3}, {'key': 2}] my_list.sort(key=lambda x: x['key'], reverse=True) print(my_list) #[{'key': 3}, {'key': 2}, {'key': 1}]
-
dict数组多关键字排序
my_list2 = [{'a': 1, 'b': 5}, {'a': 3, 'b': 3}, {'a': 5, 'b': 1}] my_list2.sort(key=lambda x: (x['a'], x['b']), reverse=True) print(my_list2) #[{'b': 1, 'a': 5}, {'b': 3, 'a': 3}, {'b': 5, 'a': 1}]
用序列类型函数sorted(list)进行排序
-
普通数组排序
my_list = [1, 2, 5, 6, 3] new_list = sorted(my_list) print(new_list) #[1, 2, 3, 5, 6]
-
dict数组排序
my_list = [{'key': 1}, {'key': 3}, {'key': 2}] new_list = sorted(my_list, key=lambda x: x['key'], reverse=True) print(new_list) # [{'key': 3}, {'key': 2}, {'key': 1}]
-
dict数组多关键字排序
my_list2 = [{'a': 1, 'b': 5}, {'a': 3, 'b': 3}, {'a': 5, 'b': 1}] new_list = sorted(my_list2, key=lambda x: (x['a'], x['b']), reverse=True) print(new_list) #[{'b': 1, 'a': 5}, {'b': 3, 'a': 3}, {'b': 5, 'a': 1}]