排序
>>> z=[11,34,-12,9,8534,12,434]
>>> z.sort()
>>> z
[-12, 9, 11, 12, 34, 434, 8534]
sort() 函数用于对原列表进行排序,如果指定参数,则使用比较函数指定的比较函数。
语法
sort()方法语法:
list.sort(cmp=None, key=None, reverse=False)
参数
参数
cmp -- 可选参数, 如果指定了该参数会使用该参数的方法进行排序。
key -- 主要是用来进行比较的元素,只有一个参数,具体的函数的参数就是取自于可迭代对象中,指定可迭代对象中的一个元素来进行排序。
reverse -- 排序规则,reverse = True 降序, reverse = False 升序(默认)。
>>> y
[[3, 9], [1, 11], [5, 34], [2, 42], [4, 98]]
>>> y=[[1,11],[2,42],[3,9],[4,98],[5,34]]
>>> y.sort(key=lambda item:item[1])
>>> y
[[3, 9], [1, 11], [5, 34], [2, 42], [4, 98]]
>>>
>>> z=[{'id':'x1','length':13},{'id':'x2','length':201},{'id':'x3','length':98},{'id':'x4','length':9}]
>>> z
[{'id': 'x1', 'length': 13}, {'id': 'x2', 'length': 201}, {'id': 'x3', 'length': 98}, {'id': 'x4', 'length': 9}]
>>> z.sort(key=lambda item: item.get('length'))
>>> z
[{'id': 'x4', 'length': 9}, {'id': 'x1', 'length': 13}, {'id': 'x3', 'length': 98}, {'id': 'x2', 'length': 201}]
>>>
>>> z=[(1,"adsfafd"),(2,"qwer"),(3,"1234asf"),(4,"ew")]
>>> z
[(1, 'adsfafd'), (2, 'qwer'), (3, '1234asf'), (4, 'ew')]
>>> z.sort(key=lambda ele:ele[1])
>>> z
[(3, '1234asf'), (1, 'adsfafd'), (4, 'ew'), (2, 'qwer')]
>>> z.sort(key=lambda ele:len(ele[1]))
>>> z
[(4, 'ew'), (2, 'qwer'), (3, '1234asf'), (1, 'adsfafd')]
>>> z.sort(key=lambda ele:len(ele[1]),reverse=True)
>>> z
[(3, '1234asf'), (1, 'adsfafd'), (2, 'qwer'), (4, 'ew')]
多属性排序
>>> z=[(1,"adsfafd"),(2,"qwer"),(3,"1234asf"),(4,"ew"),(2,"24")]
>>> z.sort(key=lambda ele:(len(ele[1]),ele[0]))
>>> z
[(2, '24'), (4, 'ew'), (2, 'qwer'), (1, 'adsfafd'), (3, '1234asf')]
>>>
#!/usr/bin/python
# 获取列表的第二个元素
def takeSecond(elem):
return elem[1]
# 列表
random = [(2, 2), (3, 4), (4, 1), (1, 3)]
# 指定第二个元素排序
random.sort(key=takeSecond)
# 输出类别
print ('排序列表:', random)