列表排序
修改原列表,不建立新列表的排序
sort(),sort(reverse=True),random.shuffle()
1 >>> a = [10,90,20,70,60,40,30,80] 2 >>> a 3 [10, 90, 20, 70, 60, 40, 30, 80] 4 >>> a.sort() 5 >>> a 6 [10, 20, 30, 40, 60, 70, 80, 90] 7 >>> a.sort(reverse=True) 8 >>> a 9 [90, 80, 70, 60, 40, 30, 20, 10] 10 >>> import range 11 Traceback (most recent call last): 12 File "<pyshell#6>", line 1, in <module> 13 import range 14 ModuleNotFoundError: No module named 'range' 15 >>> import random 16 >>> random.shuffle(a) 17 >>> a 18 [30, 80, 20, 40, 60, 70, 10, 90] 19 >>> random.shuffle(a) 20 >>> a 21 [30, 60, 40, 80, 20, 70, 10, 90]
建立新列表的排序
sorted()
1 >>> a = [10,90,20,70,60,40,30,80] 2 >>> a 3 [10, 90, 20, 70, 60, 40, 30, 80] 4 >>> id(a) 5 61080232 6 >>> a = sorted(a) 7 >>> a 8 [10, 20, 30, 40, 60, 70, 80, 90] 9 >>> id(a) 10 63216936
reverse()返回迭代器
内置函数reverse()也支持进行逆序排列,与列表对象reserve()方法不同的是,内置函数reserved()不对原列表做任何修改,只是返回一个逆序排列的迭代器对象,只使用一次
1 >>> a = [20,90,50,70] 2 >>> a 3 [20, 90, 50, 70] 4 >>> c = reserve(a) 5 Traceback (most recent call last): 6 File "<pyshell#21>", line 1, in <module> 7 c = reserve(a) 8 NameError: name 'reserve' is not defined 9 >>> c = reversed(a) 10 >>> c 11 <list_reverseiterator object at 0x04256898> 12 >>> list(c) 13 [70, 50, 90, 20] 14 >>> list(c) 15 []
列表相关的其他内置函数汇总
sum,max和min
用于返回列表中的最大值和最小值和总和
1 >>> a = [40,30,70,10] 2 >>> a 3 [40, 30, 70, 10] 4 >>> max(a) 5 70 6 >>> min(a) 7 10 8 >>> sum(a) 9 150