源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

Python使用sorted排序的方法小结

  • 时间:2021-06-25 18:09 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:Python使用sorted排序的方法小结
本文实例讲述了Python使用sorted排序的方法。分享给大家供大家参考,具体如下:
# 例1. 按照元素出现的次数来排序
seq = [2,4,3,1,2,2,3]
# 按次数排序
seq2 = sorted(seq, key=lambda x:seq.count(x))
print(seq2) # [4, 1, 3, 3, 2, 2, 2]
# 改进:第一优先按次数,第二优先按值
seq3 = sorted(seq, key=lambda x:(seq.count(x), x))
print(seq3) # [1, 4, 3, 3, 2, 2, 2]
'''
原理:
  先比较元组的第一个值,值小的在前。(注意:False < True)
  如果相等就比较元组的下一个值,以此类推。
'''

运行结果: [img]http://files.jb51.net/file_images/article/201707/2017728100656438.jpg?2017628101143[/img]
#例2.这是一个字符串排序,排序规则:小写<大写<奇数<偶数
s = 'asdf234GDSdsf23'
s2 = "".join(sorted(s, key=lambda x: (x.isdigit(),x.isdigit() and int(x) % 2 == 0,x.isupper(),x)))
print(s2) # addffssDGS33224

运行结果: [img]http://files.jb51.net/file_images/article/201707/2017728101147804.jpg?201762810127[/img]
#例3. 一道面试题:
list1 = [7, -8, 5, 4, 0, -2, -5]
#要求1.正数在前负数在后 2.正数从小到大 3.负数从大到小
list2 = sorted(list1,key=lambda x:(x<0, abs(x)))
print(list2) # [0,4,5,7,-2,-5,-8]

运行结果: [img]http://files.jb51.net/file_images/article/201707/2017728101211627.jpg?2017628101229[/img] 更多关于Python相关内容感兴趣的读者可查看本站专题:《[url=http://www.1sucai.cn/Special/663.htm]Python数据结构与算法教程[/url]》、《[url=http://www.1sucai.cn/Special/642.htm]Python函数使用技巧总结[/url]》、《[url=http://www.1sucai.cn/Special/636.htm]Python字符串操作技巧汇总[/url]》、《[url=http://www.1sucai.cn/Special/520.htm]Python入门与进阶经典教程[/url]》及《[url=http://www.1sucai.cn/Special/516.htm]Python文件与目录操作技巧汇总[/url]》 希望本文所述对大家Python程序设计有所帮助。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部