Home  >  Article  >  Backend Development  >  python使用sorted函数对列表进行排序的方法

python使用sorted函数对列表进行排序的方法

WBOY
WBOYOriginal
2016-06-10 15:16:161751browse

本文实例讲述了python使用sorted函数对列表进行排序的方法。分享给大家供大家参考。具体如下:

python提供了sorted函数用于对列表进行排序,并且可以按照正序或者倒序进行排列

#创建一个数字组成的列表
numbers = [5, 1, 4, 3, 2, 6, 7, 9]
 
#输出排序后的数字数组
print sorted(numbers)
 
#输出原始数组,并未被改变
print numbers
 
my_string = ['aa', 'BB', 'zz', 'CC', 'dd', "EE"]
 
#按字符顺序对字符串列表进行排序,默认为按字符顺序排序
print sorted(my_string)
 
#使用reverse=True按照首字符的倒序进行排序
print sorted(strs, reverse=True)
## ['zz', 'aa', 'CC', 'BB']

希望本文所述对大家的Python程序设计有所帮助。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn