当前位置:   article > 正文

python3中sorted + lambda表达式进行对可迭代对象自定义排序_ptython的sort的lamda自定义排序

ptython的sort的lamda自定义排序

在python3中,sorted可以返回一个新的已经排好序的可迭代对象
1. 列表排序

sorted(iterable, key, reverse)
  • 1
lis = [1,8,2,1,0]
print(sorted(lis, key = lambda x:x))
print(sorted(lis, key = lambda x:x), reverse = True)
  • 1
  • 2
  • 3

默认是从小到大进行排序
在这里插入图片描述
2.其他可迭代对象

from collections import Counter
res = Counter(lis)
print(res)
for item in res:
    print(item,":",res[item])

res2 = sorted(res,key = lambda x:res[x])
print(".......")
for item in res2:
    print(item,":",res2[item])
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

在这里插入图片描述
注:此处和列表不同的是,默认排序是按照频率的从大大小而不是从小到大。

本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号