内置函数_排序与逆序
排序与逆序
-
sorted()对列表、元组、字典、集合或其他可迭代对象进行排序并返回新列表,reversed()对可迭代对象进行翻转并返回可迭代的reversed对象
>>> x = list(range(11))
>>> x
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> import random
>>> random.shuffle(x)
>>> x
[7, 3, 8, 2, 4, 10, 0, 5, 6, 1, 9]
# 按转换成字符串以后的长度降序排序
>>> sorted(x,key=lambda item:len(str(item)), reverse=True)
[10, 7, 3, 8, 2, 4, 0, 5, 6, 1, 9]
>>> sorted(x,key=str) # 按转换成字符串以后的大小升序排序
[0, 1, 10, 2, 3, 4, 5, 6, 7, 8, 9]
>>> sorted(x) # 以默认规则排序
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> x
[7, 3, 8, 2, 4, 10, 0, 5, 6, 1, 9]
>>> y = ['aaaa', 'bc', 'd', 'b', 'ba']
>>> sorted(y, key = lambda item : (len(item), item)) # 先按长度排序,长度一样正常排序
['b', 'd', 'ba', 'bc', 'aaaa']
>>> reversed(y)
<list_reverseiterator object at 0x000002150A68EC88>
>>> list(reversed(y))
['ba', 'b', 'd', 'bc', 'aaaa']
>>> list(reversed(x))
[9, 1, 6, 5, 0, 10, 4, 2, 8, 3, 7]