[习题] 对此字典分别按照value 和key 如何排序?
dic1 = {'and':40, 'a':54, 'is':60, 'path':139, 'the':124, 'os':49}
In [38]: dic1 = {'and':40, 'a':54, 'is':60, 'path':139, 'the':124, 'os':49} ...: print(sorted(zip(dic1.values(),dic1.keys()))) #按value的值升序 ...: print(sorted(zip(dic1.values(),dic1.keys()),reverse=True)) #按value的值降序 ...: ...: print(sorted(zip(dic1.keys(),dic1.values()))) #按key的ascii码升序 ...: print(sorted(zip(dic1.keys(),dic1.values()),reverse=True)) #按key的ascii码降序 ...: ...: print(sorted(dic1.items(),key=lambda x:x[1],)) #按value的值升序 ...: print(sorted(dic1.items(),key=lambda x:x[1],reverse=True)) #按value的值降序 ...: ...: print(sorted(dic1.items(),key=lambda x:x[0],)) #按key的ascii码升序 ...: print(sorted(dic1.items(),key=lambda x:x[0],reverse=True)) #按key的ascii码降序 ...: [(40, 'and'), (49, 'os'), (54, 'a'), (60, 'is'), (124, 'the'), (139, 'path')] [(139, 'path'), (124, 'the'), (60, 'is'), (54, 'a'), (49, 'os'), (40, 'and')] [('a', 54), ('and', 40), ('is', 60), ('os', 49), ('path', 139), ('the', 124)] [('the', 124), ('path', 139), ('os', 49), ('is', 60), ('and', 40), ('a', 54)] [('and', 40), ('os', 49), ('a', 54), ('is', 60), ('the', 124), ('path', 139)] [('path', 139), ('the', 124), ('is', 60), ('a', 54), ('os', 49), ('and', 40)] [('a', 54), ('and', 40), ('is', 60), ('os', 49), ('path', 139), ('the', 124)] [('the', 124), ('path', 139), ('os', 49), ('is', 60), ('and', 40), ('a', 54)]
知识点: zip(),sorted(),lambda
zip:
zip函数接受任意多个(包括0个和1个)序列作为参数,返回一个tuple列表。
用法: zip(iter1 [,iter2 [...]]) --> zip object:
In [79]: a = 'abcdefg' In [80]: b = '1234567890' In [81]: zip(a,b) Out[81]: <zip at 0x1ce2b8d4fc8> In [82]: c = zip(a,b) In [83]: for i in c: ...: print(i) ...: ('a', '1') ('b', '2') ('c', '3') ('d', '4') ('e', '5') ('f', '6') ('g', '7')
sorted:
对指定可迭代对象iterable 排序并返回一个新对象,不改变原数据;key 可以设置为按str、int或者指定值(如字典的value)排序,默认是None,将按照默认对象类型排序,如果对象是str,则按ascii 码排序,如果是对象是int 数字,则按数字排序;reverse 默认升序(False),True 为降序。
sorted(iterable, key=None, reverse=False)
lambda:
最后两处lambda 比较绕,可以在( http://pythontutor.com/visualize.html#mode=display )这个网站边调试边分析x 和x[1] 的值是什么。
以下截图中,lambda表达式中x的值是一个tuple("and",40),x[1] 就表示第1个元素(40),最终sorted 就是按字典的value 来进行排序。