• 技术文章 >Python技术 >Python基础教程

    python sorted()函数的参数用法

    小妮浅浅小妮浅浅2021-08-06 09:35:24原创2843

    概念

    1、对可迭代对象中的数据进行排序,返回一个新的列表。指定 key 排序需要用到 lambda 表达式。

    语法

    sorted(iterable, key=None, reverse=False)

    参数

    iterable – 可迭代对象。

    key – 主要是用来进行比较的元素,只有一个参数,具体的函数的参数就是取自于可迭代对象中,指定可迭代对象中的一个元素来进行排序。

    reverse – 排序规则,reverse = True 降序 , reverse = False 升序(默认)。

    2、通过参数reverse=True指定倒序,参数 key指定排序时所使用的字段。

    (1)通过参数 reverse=True 指定倒序:

    >>> numbers = (4, 5, 2, 8, 9, 1, 0)
    >>> sorted(numbers, reverse=True)
    [9, 8, 5, 4, 2, 1, 0]

    (2)通过参数 key 指定排序时所使用的字段:

    >>> codes = [(‘上海’, ‘021’), (‘北京’, ‘010’), (‘成都’, ‘028’), (‘广州’, ‘020’)]
    >>> sorted(codes, key=lambda x: x[1])
    [(‘北京’, ‘010’), (‘广州’, ‘020’), (‘上海’, ‘021’), (‘成都’, ‘028’)]

    以上就是python sorted()函数参数用法的介绍,希望对大家有所帮助。更多Python学习指路:python基础教程

    本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。

    专题推荐:python sorted
    品易云
    上一篇:python help()获取函数信息 下一篇:python range()函数指定数值

    相关文章推荐

    • Python sorted函数及用法• 细说python3中sort和sorted• Python排列函数sort和sorted的区别• python字典中的sorted是什么?怎么用?• python列表如何使用sorted排序?• python中sorted怎么实现迭代排序?• python sorted中key参数怎么用?• python sorted对键和值进行排序• java中Sorted的排序• java Sorted的使用注意点

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网