【转】python笔记18-sort和sorted区别
前言
python的排序有两个方法,一个是list对象的sort方法,另外一个是builtin函数里面sorted,主要区别:
- sort仅针对于list对象排序,无返回值, 会改变原来队列顺序
- sorted是一个单独函数,可以对可迭代(iteration)对象排序,不局限于list,它不改变原生数据,重新生成一个新的队列
本篇是基于python3.6讲解的,python2会多一个cmp参数,cmp函数在python3上已经丢弃了
cmp(x,y) 函数用于比较2个对象,如果 x < y 返回 -1, 如果 x == y 返回 0, 如果 x > y 返回 1。
sort方法
1.sort是list对象的方法,通过.sort()来调用
1 >>> help(list.sort) 2 Help on method_descriptor: 3 4 sort(...) 5 L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE* 6 7 >>>
2.参数说明:
-
key 用列表元素的某个属性或函数进行作为关键字(此函数只能有一个参数)
-
reverse 排序规则. reverse = True 降序 或者 reverse = False 升序,默认升序
-
return 无返回值
3.使用方法介绍
1 # coding:utf-8 2 3 a = [-9, 2, 3, -4, 5, 6, 6, 1] 4 5 # 按从小到大排序 6 a.sort() 7 print(a) # 结果:[-9, -4, 1, 2, 3, 5, 6, 6] 8 9 # 按从大到小排序 10 a.sort(reverse=True) 11 print(a) # 结果:[6, 6, 5, 3, 2, 1, -4, -9]
4.key参数接受的是函数对象,并且函数只能有一个参数,可以自己定义一个函数,也可以写个匿名函数(lambda)
1 # coding:utf-8 2 3 a = [-9, 2, 3, -4, 5, 6, 6, 1] 4 # 按绝对值排序 5 def f(x): 6 return abs(x) 7 a.sort(key=f) 8 print(a) # 结果:[1, 2, 3, -4, 5, 6, 6, -9] 9 10 # 1、list对象是字符串 11 b = ["hello", "helloworld", "he", "hao", "good"] 12 # 按list里面单词长度倒叙 13 b.sort(key=lambda x: len(x), reverse=True) 14 print(b) # 结果:['helloworld', 'hello', 'good', 'hao', 'he'] 15 16 # 2、.list对象是元组 17 c = [("a", 9), ("b", 2), ("d", 5)] 18 19 # 按元组里面第二个数排序 20 c.sort(key=lambda x: x[1]) 21 print(c) # 结果:[('b', 2), ('d', 5), ('a', 9)] 22 23 # 3、list对象是字典 24 d = [{"a": 9}, {"b": 2}, {"d":5}] 25 26 d.sort(key=lambda x: list(x.values())[0]) 27 print(d) # 结果:[{'b': 2}, {'d': 5}, {'a': 9}]
sorted函数
1.sorted是python里面的一个内建函数,直接调用就行了
1 >>> help(sorted) 2 Help on built-in function sorted in module builtins: 3 4 sorted(iterable, key=None, reverse=False) 5 Return a new list containing all items from the iterable in ascending order. 6 7 A custom key function can be supplied to customize the sort order, and the 8 reverse flag can be set to request the result in descending order. 9 10 >>>
2.参数说明
-
iterable 可迭代对象,如:str、list、tuple、dict都是可迭代对象(这里就不局限于list了)
-
key 用列表元素的某个属性或函数进行作为关键字(此函数只能有一个参数)
-
reverse 排序规则. reverse = True 降序或者 reverse = False 升序,默认升序
-
return 有返回值值,返回新的队列
3.使用方法介绍
1 # coding:utf-8 2 3 a = [-9, 2, 3, -4, 5, 6, 6, 1] 4 5 # 按从小到大排序 6 b = sorted(a) 7 print(a) # a不会变 8 print(b) # b是新的队列 [-9, -4, 1, 2, 3, 5, 6, 6] 9 10 # 按从大到小排序 11 c = sorted(a, reverse=True) 12 print(c) # 结果:[6, 6, 5, 3, 2, 1, -4, -9]
4.可迭代对象iterable都可以排序,返回结果会重新生成一个list
1 # coding:utf-8 2 3 # 字符串也可以排序 4 5 s = "hello world!" 6 d = sorted(s) 7 print(d) # 结果:[' ', '!', 'd', 'e', 'h', 'l', 'l', 'l', 'o', 'o', 'r', 'w'] 8 9 # 元组也可以排序 10 t = (-9, 2, 7, 3, 5) 11 n = sorted(t) 12 print(n) # 结果:[-9, 2, 3, 5, 7] 13 14 # dict按value排序 15 f = {"a": 9, "b": 2, "d": 5} 16 g = sorted(f.items(), key=lambda x: x[1]) 17 print(g) # 结果:[('b', 2), ('d', 5), ('a', 9)]
转自:
https://www.cnblogs.com/yoyoketang/p/9151195.html
记录每天生活的点点滴滴,呵呵呵呵呵呵

浙公网安备 33010602011771号