首页 > 文章列表 > python列表排序的两种方式

python列表排序的两种方式

Python 列表
391 2022-08-07

1、使用sort()永久排序列表。

用sort()方法改变原始列表。若要逆转排序,只需将参数reverse=True传递给sort()。

>>> 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()。

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

本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。