首页 > 代码库 > Python基础课:列表方法sort(), reverse()

Python基础课:列表方法sort(), reverse()

 1 >>> x = list(range(11))
 2 >>> import random
 3 >>> random.shuffle(x)  #随机乱序
 4 >>> x
 5 [4, 2, 5, 7, 0, 10, 9, 8, 1, 3, 6]
 6 >>> x.sort(key=lambda i:len(str(i)), reverse=True) #指定规则排序
 7 >>> x
 8 [10, 4, 2, 5, 7, 0, 9, 8, 1, 3, 6]
 9 >>> x.reverse()
10 >>> x
11 [6, 3, 1, 8, 9, 0, 7, 5, 2, 4, 10]
12 >>> x.sort(key=str)  #按转换为字符串后的大小排序
13 >>> x
14 [0, 1, 10, 2, 3, 4, 5, 6, 7, 8, 9]
15 >>> x.sort()
16 >>> x
17 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
18 >>> sorted(x, key=str)
19 [0, 1, 10, 2, 3, 4, 5, 6, 7, 8, 9]
20 >>> x  #x没有改变
21 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
22 >>> reversed(x)  #逆序
23 <list_reverseiterator object at 0x0000016AD4A74780>
24 >>> list(reversed(x))
25 [10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
26 >>> x
27 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
28 >>> 

 

Python基础课:列表方法sort(), reverse()