Python 列表排序详解

作者:莫导 时间:2022-08-14 05:05:21 

在Python中,对列表进行排序有两种方法。

一种是调用 sort() 方法,该方法没有返回值,对列表本身进行升序排序。


cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.sort()
print(cars)

输出:

['audi', 'bmw', 'subaru', 'toyota']

另一种方法是使用 sorted() 函数,该函数会返回升序排序的列表,同时不影响原本的列表。


cars = ['bmw', 'audi', 'toyota', 'subaru']

print("Here is the original list:")
print(cars)

print("\nHere is the sorted list:")
print(sorted(cars))

print("\nHere is the original list again:")
print(cars)

输出:


Here is the original list:
['bmw', 'audi', 'toyota', 'subaru']

Here is the sorted list:
['audi', 'bmw', 'subaru', 'toyota']

Here is the original list again:
['bmw', 'audi', 'toyota', 'subaru']

来源:https://blog.csdn.net/m0_59838087/article/details/120680971

标签:Python,列表,排序
0
投稿

猜你喜欢

  • 详解python websocket获取实时数据的几种常见链接方式

    2023-09-20 08:22:23
  • python中单双下划线的区别对比分析

    2023-12-18 23:58:45
  • VUE预渲染及遇到的坑

    2023-07-02 17:08:34
  • Python编程实现及时获取新邮件的方法示例

    2022-09-28 16:52:15
  • SqlServer 多种分页方式 详解(含简单速度测试)

    2024-01-15 07:28:04
  • pandas多层索引的创建和取值以及排序的实现

    2023-07-09 23:12:54
  • 15行Python代码带你轻松理解令牌桶算法

    2021-05-05 01:18:05
  • 关于反爬虫的一些简单总结

    2022-09-21 18:38:59
  • 详解python中docx库的安装过程

    2023-01-21 18:32:36
  • 浅谈keras的深度模型训练过程及结果记录方式

    2023-08-11 03:17:46
  • ProC 连接Oracle代码

    2009-06-10 18:12:00
  • 在VScode中引用自定义模块问题

    2023-08-13 03:50:37
  • BERT vs GPT自然语言处理中的关键差异详解

    2022-04-01 08:15:36
  • asp中Adodb.Stream 的使用说明

    2007-09-11 13:53:00
  • 纯ASP(VBscript)写的全球IP地址搜索程序

    2007-09-27 13:28:00
  • Python 操作 MongoDB 讲解详细

    2021-11-28 10:00:46
  • 微信小程序实现渐入渐出动画效果

    2024-04-23 09:32:53
  • python 使用xlsxwriter循环向excel中插入数据和图片的操作

    2023-01-30 15:08:47
  • Python实现Kerberos用户的增删改查操作

    2023-07-29 09:39:52
  • 使用 Python 读取电子表格中的数据实例详解

    2023-10-15 02:40:57
  • asp之家 网络编程 m.aspxhome.com