华域联盟 Python Python 列表排序详解

Python 列表排序详解

文章目录[隐藏]

在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']

总结

本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注华域联盟的更多内容!

您可能感兴趣的文章:

本文由 华域联盟 原创撰写:华域联盟 » Python 列表排序详解

转载请保留出处和原文链接:https://www.cnhackhy.com/38253.htm

本文来自网络,不代表华域联盟立场,转载请注明出处。

作者: sterben

发表回复

联系我们

联系我们

2551209778

在线咨询: QQ交谈

邮箱: [email protected]

工作时间:周一至周五,9:00-17:30,节假日休息

关注微信
微信扫一扫关注我们

微信扫一扫关注我们

关注微博
返回顶部