高阶函数sorted()的用法详解
sorted(list, key, reverse)
list是给定的列表;
key是排序过程调用的函数,也就是排序依据
reverse是降序还是升序,默认为False升序,True降序
1 l1 = [1,3,5,-2,-4,-6] 2 l2 = sorted(l1,key=abs) 3 print(l1) 4 print(l2) 5 6 # 7 [1, 3, 5, -2, -4, -6] 8 [1, -2, 3, -4, 5, -6]
1 l = [[1,2],[3,4,5,6],(7,),'123'] 2 print(sorted(l,key=len)) 3 4 # 5 [(7,), [1, 2], '123', [3, 4, 5, 6]]
1 word_dict = {'apple':20, 'love':15} 2 sorted_word_dict = sorted(word_dict.items(), key=lambda d:d[1]) 3 print(sorted_word_dict) 4 5 # 6 [('love', 15), ('apple', 20)]