修改原列表,不建新列表的排序
>>> a [10, 20, 30, 40, 50, 20, 30, 20, 30] >>> id(a) 52279816 >>> a.sort() # 默认是升序排列 >>> a [10, 20, 20, 20, 30, 30, 30, 40, 50] >>> id(a) 52279816
>>> a = [10, 20, 30, 40, 50, 20, 30, 20, 30]
>>> id(a)
63441496
>>> a.sort(reverse=True) #降序排列
>>> a
[50, 40, 30, 30, 30, 20, 20, 20, 10]
>>> id(a)
63441496
>>> a = [10, 20, 30, 40, 50, 20, 30, 20, 30]
>>> import random
>>> random.shuffle(a) # 打乱顺序
>>> a
[20, 30, 40, 50, 30, 20, 20, 30, 10]
>>> random.shuffle(a)
>>> a
[20, 30, 10, 40, 30, 20, 20, 50, 30]
>>> random.shuffle(a)
>>> a
[40, 10, 50, 20, 30, 30, 20, 30, 20]
建新列表的排序
也可以通过内置函数sorted()进行排序,这个方法返回新列表,不对原列表做修改。
后续补充
列表相关的其他内置函数汇总
max和min
用于返回列表中最大和最小值
>>> a [40, 10, 50, 20, 30, 30, 20, 30, 20] >>> max(a) 50 >>> min(a) 10
sum
对数值型列表的所有元素进行求和操作,对非数值型列表运算则会报错。
>>> a [40, 10, 50, 20, 30, 30, 20, 30, 20] >>> sum(a) 250 >>> b = [2,5,6,7,'king'] >>> sum(b) Traceback (most recent call last): File "<pyshell#125>", line 1, in <module> sum(b) TypeError: unsupported operand type(s) for +: 'int' and 'str'