使用lambda函数取出字典中的value:d = {'a': 24, 'g': 52, 'i': 12, 'k': 33}print(list(map(lambda x:x[1],d.items())))[24, 52, 12, 33]使用sort函数排序
d_1=sorted(d.items(),key=lambda x:x[1],reverse=False)
print('d_1:',d_1)d_1: [('i', 12), ('a', 24), ('k', 33), ('g', 52)]
d_2=sorted(d.items(),key=lambda x:x[1],reverse=True)print('d_2:',d_2)d_2: [('g', 52), ('k', 33), ('a', 24), ('i', 12)]
"""按照每个元组元素的长度排序"""l = [(1,5,3),(1,3,6,3),(1,1,2,4,5,6),(1,9)]def func(item): return len(item)l1=sorted(l,key=func)print(l1)[(1, 9), (1, 5, 3), (1, 3, 6, 3), (1, 1, 2, 4, 5, 6)]l2=sorted(l,key=lambda x:len(x))print(l2)
[(1, 9), (1, 5, 3), (1, 3, 6, 3), (1, 1, 2, 4, 5, 6)]
来源:博客园
作者:任修行
链接:https://www.cnblogs.com/testerren/p/11410079.html