(一)Python入门-3序列:07列表-排序-revered逆序-max-min-sum

一:修改原列表,不建新列表的排序

 1 >>> a = [20,10,50,30,40]
 2       
 3 >>> id(a)
 4       
 5 1983361589064
 6 >>> a.sort()    #默认升序排列
 7       
 8 >>> a
 9       
10 [10, 20, 30, 40, 50]
11 >>> a.sort(reverse=True)  #降序排序
12       
13 >>> a
14       
15 [50, 40, 30, 20, 10]
16 >>> import random
17       
18 >>> random.shuffle(a)  #打乱顺序,随机排序
19       
20 >>> a
21       
22 [40, 50, 30, 20, 10]
23 >>> random.shuffle(a)
24       
25 >>> a
26       
27 [10, 30, 40, 20, 50]
28 >>> id(a)
29       
30 1983361589064

二:建新列表的排序

  可以通过内置函数sorted()进行排序,这个方法返回新列表,不对原列表做修改。

 1 >>> a = [20,10,50,30,40]
 2       
 3 >>> id(a)
 4       
 5 1983366024968
 6 >>> a = sorted(a)   #默认升序
 7       
 8 >>> a
 9       
10 [10, 20, 30, 40, 50]
11 >>> id(a)
12       
13 1983365869704
14 >>> a = [20,10,50,30,40]
15       
16 >>> id(a)
17       
18 1983361588936
19 >>> b = sorted(a)
20       
21 >>> b
22       
23 [10, 20, 30, 40, 50]
24 >>> id(a)
25       
26 1983361588936
27 >>> id(b)
28       
29 1983361522952
30 >>> c = sorted(a,reverse=True)   #降序
31       
32 >>> c
33       
34 [50, 40, 30, 20, 10]
35 >>> id(c)
36       
37 1983366024968

  通过上面操作,我们可以看出,生成的列表对象b和c都是完全新的列表对象。

三:reversed()返回迭代器

  内置函数reversed()也支持进行逆序排列,与列表对象 reverse()方法不同的是,内置函数reversed()不对原列表做任何修改,只返回一个逆序排列的迭代器对象。

 1 >>> a = [20,10,50,30,40]
 2       
 3 >>> c = reversed(a)
 4       
 5 >>> c
 6       
 7 <list_reverseiterator object at 0x000001CDC9D1E3C8>
 8 >>> list(c)
 9       
10 [40, 30, 50, 10, 20]
11 >>> list(c)
12       
13 []

  打印输出c发现提示是:list_reverseiterator。也就是一个迭代对象。同时,我们使用 list(c)进行输出,发现只能使用一次。第一次输出了元素,第二次为空。那是因为迭代对象 在第一次时已经遍历结束了,第二次不能再使用。

四:列表相关其他内置函数

  1、max和min

    用于返回列表中最大和最小值。

1 >>> a = [20,10,50,30,40]
2       
3 >>> max(a)
4       
5 50
6 >>> min(a)
7       
8 10

  2、sum

    对数值型列表的所有元素进行求和操作,对非数值型列表运算则会报错。

1 >>> a = [20,10,50,30,40]
2       
3 >>> sum(a)
4       
5 150

猜你喜欢

转载自www.cnblogs.com/jack-zh/p/10816741.html