
1、使用sort()永久排序列表。
用sort()方法改变原始列表。若要逆转排序,只需将参数reverse=True传递给sort()。
1 2 3 4 5 6 7 8 | >>> list
[ 'zhangsan' , 'lisi' , 'bob' , 'alex' ]
>>> list.sort()
>>> list
[ 'alex' , 'bob' , 'lisi' , 'zhangsan' ]
>>> list.sort(reverse=True)
>>> list
[ 'zhangsan' , 'lisi' , 'bob' , 'alex' ]
|
2、用函数sorted()临时排序列表。
函数sorted()允许按特定顺序显示列表元素,而不影响列表中的原始排列顺序。
若要反转排序,只需将参数reverse=True传送到sorted()。
1 2 3 4 5 6 7 8 9 | >>> list = [ 'douglas' , 'alex' , 'solo' , 'super' ]
>>> sorted(list)
[ 'alex' , 'douglas' , 'solo' , 'super' ]
>>> list
[ 'douglas' , 'alex' , 'solo' , 'super' ]
>>> sorted(list, reverse=True)
[ 'super' , 'solo' , 'douglas' , 'alex' ]
>>> list
[ 'douglas' , 'alex' , 'solo' , 'super' ]
|
以上就是python列表排序的两种方式,希望对大家有所帮助。更多Python学习指路:python基础教程
本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。