• Python3-笔记-C-005-函数-sorted


    # sorted(iterablekey=None,reverse=False)
    # key接受一个函数,这个函数只接受一个元素,默认为None
    # reverse是一个布尔值。默认为False排在前,True排在后,升序,即符合条件的往后排

    # 按照年龄来排序
    students = [('john', 'A', 15), ('jane', 'B', 12), ('dave','B', 10)]
    r1 = sorted(students, key=lambda s: s[2])
    # <class 'list'>: [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]


    # 字符串排序,排序规则:小写<大写<奇数<偶数
    s = 'asdf234GDSdsf23'
    r3 = "".join(sorted(s, key=lambda x: (x.isdigit())))
    # 数字在后 'asdfGDSdsf23423'
    r4 = "".join(sorted(s, key=lambda x: (x.isdigit(), x.isdigit() and int(x) % 2 == 0)))
    # 数字在后,偶数在后 'asdfGDSdsf33242'
    r5 = "".join(sorted(s, key=lambda x: (x.isdigit(),x.isdigit() and int(x) % 2 == 0, x.isupper())))
    # 数字在后,偶数在后,大写在后 'asdfdsfGDS33242'
    r6 = "".join(sorted(s, key=lambda x: (x.isdigit(),x.isdigit() and int(x) % 2 == 0, x.isupper(), x)))
    # 数字在后,偶数在后,大写在后,按字母或数字升序排 'addffssDGS33224'


    # 正数在前负数在后,正数从小到大,负数从大到小
    list1 = [4, -8, 7, 5, 0, -2, -5]
    r1 = sorted(list1, key=lambda x: (x < 0))
    # 先按照正负排先后,将负数移到后面 <class 'list'>: [4, 7, 5, 0, -8, -2, -5]
    r2 = sorted(list1, key=lambda x: (x < 0, abs(x)))
    # 再按照大小排先后 <class 'list'>: [0, 4, 5, 7, -2, -5, -8]
  • 相关阅读:
    wppay免登录付费查看隐藏内容/付费资源下载
    个人网站html5雪花飘落代码JS特效下载
    HTML5 audio 如何实现播放多个MP3音频
    网站html代码解析
    vue-webpack模板升级到webpack4
    npm安装cnpm
    单个div充满屏幕的CSS方法
    vue监听滚动事件-元素固定位置显示
    HTML5中判断横屏竖屏
    The META for Mobile terminal
  • 原文地址:https://www.cnblogs.com/vito13/p/7730039.html
Copyright © 2020-2023  润新知