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

总结

本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注www.887551.com的更多内容!