pythonsort()怎么排序
python中的sort()函数只能应用在列表list上,而sorted可以对所有可迭代的对象进行排序的操作
sort方法会在原list上直接进行排序,不会创建新的list。而sorted方法不会对原来的数据做任何改动,排序后的结果是新生成的。如果我们不需要原来的数据而且数据是list类型,可以用sort方法,能够节省空间。否则要用sorted方法。
sort
在python2中,sort方法可以有3个参数:key、cmp和reverse。但在python3中取消了cmp这个参数,只有key和reverse两个可选参数。参数reverse指定排序是正序还是倒序,默认是正序FALSE,不在多说。参数key指定了只含一个参数的方法,这个方法用来从列表的每个元素中提取比较键。可以看看下面几个例子:
1.通过元素长度排序
strlist=["bbb","ccc","bac","ab","ba"]
strlist.sort(key=len)
print(strlist)
打印结果如下:
['ab','ba','bbb','ccc','bac']
2.通过元素的字符顺序
strlist=["bbb","BBB","bAc","ab","bac"]
strlist.sort()print(strlist)
strlist.sort(key=str.lower)print(strlist)
打印结果如下:
['BBB','ab','bAc','bac','bbb']
['ab','bAc','bac','BBB','bbb']
3.更复杂一点的排序:list里的元素是一个字典,通过字典的某个属性值排序。下面是通过学生的年龄排序
student=[{"name":"小C","age":12,"score":90},
{"name":"小D","age":13,"score":84},
{"name":"小A","age":14,"score":85},
{"name":"小E","age":15,"score":89},
{"name":"小F","age":12,"score":88}]
student.sort(key=lambdaa:a["age"])
print(student)
打印结果如下(换行是我自己处理的):
[{'name':'小C','age':12,'score':90},
{'name':'小F','age':12,'score':88},
{'name':'小D','age':13,'score':84},
{'name':'小A','age':14,'score':85},
{'name':'小E','age':15,'score':89}]
那么原来的cmp参数有的功能实现不了了吗?当然能,可以通过从functools库里引入cmp_to_key来解决,看下面几个例子:
1.数组的倒序
fromfunctoolsimportcmp_to_key
list=[5,4,3,2,1]
list.sort(key=cmp_to_key(lambdaa,b:b-a))
print(list)
打印结果如下:
[5,4,3,2,1]
2.把数组排成最小的数里python的解法可以通过如下方式解答(注意倒数第3行,把map类型转成了list类型):
fromfunctoolsimportcmp_to_key
classSolution:
defPrintMinNumber(self,numbers):
numbers=list(map(str,numbers))
numbers.sort(key=cmp_to_key(lambdas1,s2:int(s1+s2)-int(s2+s1)))
return"".join(numbers)
由于sort只有list类型才可以用,所以用的更普遍的是sorted方法。
以上内容为大家介绍了python培训之sort()怎么排序,希望对大家有所帮助,如果想要了解更多Python相关知识,请关注IT培训机构:千锋教育。

相关推荐HOT
更多>>
python函数标注是什么
python函数标注是什么在参数的使用方法中,还有一种解包的情况是需要我们掌握的。比如,将列表或者字典的值转换为函数的参数,就需要用到参数解...详情>>
2023-11-14 14:13:35
python正负索引的使用
python正负索引的使用本文教程操作环境:windows7系统、Python3.9.1,DELLG3电脑。1、说明使用正索引(从左至右)、负索引(从右至左)访问元素,时...详情>>
2023-11-14 13:45:04
python垃圾回收的机制过程
python垃圾回收的机制过程本文教程操作环境:windows7系统、Python3.9.1,DELLG3电脑。1、步骤(1)收集所有容器对象(list,dict,tuple,customClas...详情>>
2023-11-14 13:05:15
pythontry语句的执行原理
pythontry语句的执行原理1、原理分析(1)执行try子句(try和except关键字之间的多行语句)。(2)如果没有异常发生,则跳过except子句并完成try语句...详情>>
2023-11-14 09:37:35热门推荐
技术干货






