python中sort和sorted方法区别

python3中sort()和sorted()都可以用来排序,但二者有以下两个最主要的区别:

sort只能应用在列表list上,而sorted可以对所有可迭代的对象进行排序的操作

sort方法会在原list上直接进行排序,不会创建新的list。而sorted方法不会对原来的数据做任何改动,排序后的结果是新生成的。如果我们不需要原来的数据而且数据是list类型,可以用sort方法,能够节省空间。否则要用sorted方法。

我们首先看看sort方法

l = [1,9,3,4,6,7,5]
l.sort()
print(l)
#打印结果
[1, 3, 4, 5, 6, 7, 9]

由于sort在原来list内部进行排序,不会返回一个新的list,所以我们需要像上面那样才能打印出结果,不然会返回None

sort函数中海油两个参数,一个是key,一个是reverse

key可以用来作为排序的依据,例如key=len来根据每个元素的长度来排列,key=str.lower会根据字母大小写来排列

reverse是排序方法

l = [1,9,3,4,6,7,5]
l.sort(reverse=True)
print(l)
打印结果
[9, 7, 6, 5, 4, 3, 1]

如果是复合型的列表排序,可以灵活使用匿名函数来指定排序的key

l = [{"allocationID": "3db9ae83-057f-47e8-be95-71545febc865", "duration": "394"},
    {"allocationID": "5e2faf54-7275-4f08-ace7-d2ce2184a6f4", "duration": "377"},
    {"allocationID": "49e6d4ae-d9d8-44f0-ba07-8a761861bdd1", "duration": "378"},
    {"allocationID": "27cd24fd-aa62-45a8-b3c1-6ad3871d97eb", "duration": "192"}]
l.sort(key=lambda x: x["duration"], reverse=False)

接下来我们看看sorted排序,所有的迭代对象都可以使用sorted来排序

l = [1,9,3,4,6,7,5]
d = sorted(l)
print(d)
#打印结果
[1, 3, 4, 5, 6, 7, 9]

sorted也是有key和reverse这两个参数,用法同上

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://sulao.cn/post/370.html

我要评论

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。