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

    python列表排序的两种方式

    小妮浅浅小妮浅浅2021-06-11 17:18:11原创14921

    1、使用sort()永久排序列表。

    用sort()方法改变原始列表。若要逆转排序,只需将参数reverse=True传递给sort()。

    >>> list
    ['zhangsan', 'lisi', 'bob', 'alex']
    >>> list.sort()
    >>> list
    ['alex', 'bob', 'lisi', 'zhangsan']
    >>> list.sort(reverse=True)
    >>> list
    ['zhangsan', 'lisi', 'bob', 'alex']

    2、用函数sorted()临时排序列表。

    函数sorted()允许按特定顺序显示列表元素,而不影响列表中的原始排列顺序。

    若要反转排序,只需将参数reverse=True传送到sorted()。

    >>> list = ['douglas','alex','solo','super']
    >>> sorted(list)
    ['alex', 'douglas', 'solo', 'super']
    >>> list
    ['douglas', 'alex', 'solo', 'super']
    >>> sorted(list, reverse=True)
    ['super', 'solo', 'douglas', 'alex']
    >>> list
    ['douglas', 'alex', 'solo', 'super']

    以上就是python列表排序的两种方式,希望对大家有所帮助。更多Python学习指路:python基础教程

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

    专题推荐:python 列表
    品易云
    上一篇:python删除元素的使用条件 下一篇:python for…in循环的使用

    相关文章推荐

    • python爬虫怎么用• python爬虫怎么运行• python怎么爬虫• python XML数据是什么• python ElementTree解析的方法• Python有哪些命令行参数解析模块?• Python脚本如何指定文件• Python Elasticsearch DSL如何使用• python loguru如何记录日志• python使用loguru操作日志• python input()的特性• python列表中有哪些内置函数• python系统内置方法如何获取• python列表追加元素出错的解决• python匿名函数lambda的注意点• python匿名函数的好处

    全部评论我要评论

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

  • 取消发布评论
  • 

    Python学习网