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编程 从入门到实践(第2版)》 埃里克 · 马瑟斯著 袁国忠译

猜你喜欢

转载自blog.csdn.net/m0_59838087/article/details/120680971
今日推荐