网络编程
位置:首页>> 网络编程>> Python编程>> Python 列表排序详解

Python 列表排序详解

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

标签: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']

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

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com