在使用python中的字典存储key/value值的时候,因为当中的存储是无需的,而在输出的时候需要对输出结果进行排序。这个就是sorted的用武之地。
sorted
( iterable[, cmp[, key[, reverse]]])
Return a new sorted list from the items in iterable.
The optional arguments cmp, key, and reverse have the same meaning as those for the list.sort() method (described in section 3.6.4).
cmp specifies a custom comparison function of two arguments (iterable elements) which should return a negative, zero or positive number depending on whether the first argument is considered smaller than, equal to, or larger than the second argument: "cmp=lambda x,y: cmp(x.lower(), y.lower())"
key specifies a function of one argument that is used to extract a comparison key from each list element: "key=str.lower"
reverse is a boolean value. If set to True, then the list elements are sorted as if each comparison were reversed.
In general, the key and reverse conversion processes are much faster than specifying an equivalent cmp function. This is because cmp is called multiple times for each list element while key and reverse touch each element only once.
New in version 2.4.
而对于字典的操作见实例:
一:按照key进行排序
strings={'a':2,'b':3}
sorted(strings.iteritems(),key=lambda d:d[0],reverse=True)
#outout [('b', 3), ('a', 2)]
二:按照value进行排序
strings={'a':5,'z':1,'b':7}
sorted(strings.iteritems(),key=lambda d:d[1])
#output [('z', 1), ('a', 5), ('b', 7)]
分享到:
相关推荐
给出了字典排序求取全排列的算法实现,JAVA
编写一个对输入的英文单词按照字典排序的程序,界面如图,当在一个文本域输入若干个英文字单词,单击字典排序按钮,另一个文本域 对输入的英文单词进行排序;当按清空按钮,另一个文本区域的内容同时清空。要求通过...
字典排序,c语言
用c++实现的字典排序,也就是基数排序,是数据结构里的经典必学算法
字典排序字典序字典字典排序字典字典排序字典字典排序字典字典排序字典字典排序字典字典排序字典字典排序字典字典排序字典字典排序字典字典排序字典字典排序字典字典排序字典字典排序字典字典排序字典
利用c语言实现字典排序算法,可以简单的使用。
根据字典排序确定下一个序列,详细分析过程。
本文实例分析了python字典排序的方法。分享给大家供大家参考。具体如下: 1、 准备知识: 在python里,字典dictionary是内置的数据类型,是个无序的存储结构,每一元素是key-value对: 如:dict = {‘username’:’...
对于任意一个有1到n的正整数安一定的顺序输出其所有可能的组合
主要介绍了Python使用lambda表达式对字典排序操作,结合实例形式分析了lambda表达式实现字典按键排序、按值排序、多条件排序相关操作技巧,需要的朋友可以参考下
2.可以支持升序、降序、字典排序等多种顺序要求 3.可以随意增加排序算法和顺序要求,保证其他程序不修改 4.减少程序代码中逻辑上的冗余 5.至少用两种方案编程实现该程序包,并说明两个方案的优缺点 6.提交设计报告,...
动态规划实现的字典排序,构建最优二叉树,小心你的内存啊!
实现在一个多行文本区输入内容,在另一文本域中按字典排序,点击按钮两者内容被清空
对数字进行编码使其对字典排序后仍有序,在这里面主要举了几个详细的例子,相信大家看了后会明白的。
本压缩包包含2个c++源代码,本人写是觉得很复杂,弄好和希望和大家共享
Go语言实现的全球唯一字典排序标识符(ULID)
本程序以输入下述8个国家名字的字符串为例,讲述字典排序的方法。 如:CHINA、JAPAN、KOREA、INDIA、CANADA、AMERICAN、ENGLAND和FRANCE,将这些国名按字典顺序排序。
iOS中对字典进行排序,博客地址:http://blog.csdn.net/ioswyl88219/article/details/17805837
字典 自动排序 c# 对话框 输入一个单词后自动跳出该含有该单词的所有单词
将你输入的英文单词按照字典自动排序,在word.txt文件中输入原始英文,在output.txt中保存排序的单词