Python 列表排序详解

这篇文章主要介绍了Python中对列表排序实例,本文给出了9个List的排序实例,需要的朋友可以参考下,希望能够给你带来帮助

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

总结

本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注0133技术站的更多内容!

以上就是Python 列表排序详解的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » python