<转>python字典排序 关于sort()、reversed()、sorted()
一、Python的排序
1、reversed()
这个很好理解,reversed英文意思就是:adj. 颠倒的;相反的;(判决等)撤销的
print list(reversed(['dream','a','have','I']))
#['I', 'have', 'a', 'dream']
2、让人糊涂的sort()与sorted()
在Python 中sorted是内建函数(BIF),而sort()是列表类型的内建函数list.sort()。
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 Mutable Sequence Types).
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()). The default value is None.
key specifies a function of one argument that is used to extract a comparison key from each list element: key=str.lower. The default value is None (compare the elements directly).
reverse is a boolean value. If set to True, then the list elements are sorted as if each comparison were reversed.
#字符串排序使用是字典序,而非字母序
"""sorted()按照字典序排序"""
lis = ['a','c','z','E','T','C','b','A','Good','Tack']
print sorted(lis) #['A', 'C', 'E', 'Good', 'T', 'Tack', 'a', 'b', 'c', 'z']
关于字典序:
可参考百度百科。http://baike.baidu.com/view/4670107.htm
根据ASCII排,具体如下:
0-9(对应数值48-59);
A-Z(对应数值65-90);
a-z(对应数值97-122);------------
标准序: 短在前,长在后,等长的依次比字母,
如to < up < cap < cat < too < two <boat < boot < card
字典序: 依次比字母,
如boat < boot <cap < card < cat < to < too< two < up更有甚者说字典序就是字典的排序,像字典一样。我一直没有找到权威的说明,什么是字典序????求答案!!
sort()
s.sort([cmp[, key[, reverse]]])
三、Python的字典排序
1、关于Python字典的一些特征
无序:
字典,形如 dic = {'a':1 , 'b':2 , 'c': 3},字典中的元素没有顺序,所以dic[0]是有语法错误的。
无重:
不可以有重复的键值,所以 dic.add['c'] = 4后,字典变成 {'a':1 , 'b':2 , 'c': 4}.
2、根据“键”或“键值”进行不同顺序的排序
函数原型:sorted(dic,value,reverse)
解释:dic为比较函数,value 为排序的对象(这里指键或键值),
reverse:注明升序还是降序,True--降序,False--升序(默认)
3、例子:
dic = {'a':31, 'bc':5, 'c':3, 'asd':4, '33':56, 'd':0}
想把dic的value按照从大到小排序(value都是整数)。
dic = {'a':31, 'bc':5, 'c':3, 'asd':4, '33':56, 'd':0}
print sorted(dic.iteritems(), key=lambda d:d[1], reverse = False )
#[('d', 0), ('c', 3), ('asd', 4), ('bc', 5), ('a', 31), ('33', 56)]
解释如下:
(1)、dic.iteritems(),返回字典键值对的元祖集合
print dic.iteritems() #<dictionary-itemiterator object at 0x00B71A80> for obj in dic.iteritems():
print obj,obj[0],obj[1] #('a', 31) a 31
#('c', 3) c 3
#('d', 0) d 0
#('bc', 5) bc 5
#('33', 56) 33 56
#('asd', 4) asd 4
(2)、关于排序对象
上述已经说过,value(或key)为排序的对象(这里指键或键值),然而为什么使用lambda函数呢,这里请参阅:点击阅读
key=lambda d:d[1] 是将键值(value)作为排序对象。
key = lambda d:d[1]
for i in dic.iteritems():
print key(i), #输出31 3 0 5 56 4,这些都是字典dic的值
如果选择 key = lambda d:d[0],则选择【键Key】作为排序对象。
(3)、reverse
reverse 是否反向,reverse=Ture表示反向。
(4)、注意:
sorted(dic.iteritems(), key=lambda d:d[1], reverse = False )将每一项dic.iteritems()键值对的元祖进行迭代,每一项都作为参数传入key()函数(我说的是这个:key=lambda d:d[1],)中。
4、回顾
lis = ['a','bc','c','asd','33','d']
print sorted(lis) #['33', 'a', 'asd', 'bc', 'c', 'd']
依次比字母, 如boat < boot <cap < card < cat < to < too< two < up
5.问题
具体实例可参考:[**python的排序函数sort,sorted在列表排序和字典排序中的应用详解和举例**](http://wangwei007.blog.51cto.com/68019/1100742)
现在有这种情况,排序中排序。如大题号排序,然后大题对应的小题号也排序,如下:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
lis = [{'Big':3, 'small':2},{'Big':3, 'small':4},{'Big':2, 'small':2}, {'Big':3, 'small':1},{'Big':2, 'small':1},{'Big':1, 'small':1}]# 大题号排序li = sorted(lis, key=lambda s: s['Big'])# 输出:#[{'small': 1, 'Big': 1}, {'small': 2, 'Big': 2}, {'small': 1, 'Big': 2}, {'small': 2, 'Big': 3}, {'small': 4, 'Big': 3}, {'small': 1, 'Big': 3}]# 小题号排序:sort_ff = []no = set([i['Big'] for i in li])for obj in no:li_ = []for i in ff:if i['Big'] == obj:li_.append(i)l = sorted(li_, key=lambda s: s['small'])for j in l:sort_ff.append(j)# 输出结果:[{'small': 1, 'Big': 1}, {'small': 1, 'Big': 2}, {'small': 2, 'Big': 2}, {'small': 1, 'Big': 3}, {'small': 2, 'Big': 3}, {'small': 4, 'Big': 3}] |
善用sort() 或 sorted(), a.sort() 已改变其结构,b = a.sort() 是错误的写法! 而 sorted(a, ...)并没有改变a的结构。
<转>python字典排序 关于sort()、reversed()、sorted()的更多相关文章
- python 字典排序 关于sort()、reversed()、sorted()
一.Python的排序 1.reversed() 这个很好理解,reversed英文意思就是:adj. 颠倒的:相反的:(判决等)撤销的 print list(reversed(['dream','a ...
- python 列表排序方法sort、sorted技巧篇
Python list内置sort()方法用来排序,也可以用python内置的全局sorted()方法来对可迭代的序列排序生成新的序列. 1)排序基础 简单的升序排序是非常容易的.只需要调用sorte ...
- Python 的排序方法 sort 和 sorted 的区别
使用 sort() 或内建函数 sorted() 对列表进行排序.它们之间的区别有两点: sort() 方法是对原列表进行操作,而 sorted() 方法会返回一个新列表,不是在原来的基础上进行操作. ...
- Python中的排序方法sort(),sorted(),argsort()等
python 列表排序方法sort.sorted技巧篇 转自https://www.cnblogs.com/whaben/p/6495702.html,学习参考. Python list内置sort( ...
- 深入Python(1): 字典排序 关于sort()、reversed()、sorted()
http://www.cnblogs.com/BeginMan/p/3193081.html 一.Python的排序 1.reversed() 这个很好理解,reversed英文意思就是:adj. 颠 ...
- Python字典排序
利用引出一个例子来理解 例如:比如使用Python字典排序,d={'a':1,'c':3,'b':2}按值升序排列,我们可以用sorted高阶函数或者用列表的.sort()方法.下面具体阐述两种排序方 ...
- Python 使用 lambda() 结合sort() 或 sorted() 对列表嵌套字典格式的数据进行排序
1.使用sort()方法进行排序 my_list = [{"age":65, "money":5}, {"age":35, "mo ...
- [python学习] 语言基础—排序函数(sort()、sorted()、argsort()函数)
python的内建排序函数有 sort.sorted两个. 1.基础的序列升序排序直接调用sorted()方法即可 ls = list([5, 2, 3, 1, 4]) new_ls = sorted ...
- python排序函数sort()与sorted()区别
sort是容器的函数:sort(cmp=None, key=None, reverse=False) sorted是python的内建函数:sorted(iterable, cmp=None, key ...
随机推荐
- Maven的生命周期是为了对所有的构建过程进行了抽象了,便于统一。
Maven的生命周期是为了对所有的构建过程进行了抽象了,便于统一. clean(清理) cleanup(清理所有) 此生命周期旨在给工程做清理工作,它主要包含以下阶段: pre-clean - 执行项 ...
- Swing文本域的编辑
1..setEditable(false); 设置文本域不可编辑 2..setHorizontalAlignment(JTextField.CENTER); // 设置文本的水平对齐方式 有效值包括: ...
- java 项目 存入mysql后 变问号 MySql 5.6 (X64) 解压版 1067错误与编码问题的解决方案
[参考]MySQL 5.7.19 忘记密码 重置密码 my.ini示例 服务启动后停止 环境 Java环境JDK1.8 安装好了 mysql-5.6.38-winx64 idea2016(64) ...
- html 禁用点击事件
1.css禁用鼠标点击事件 .disabled { pointer-events: none; } 注:(这个没有试过) jquery禁用a标签方法1 $(document).ready(functi ...
- [AngularJS]ng-repeat指令要点
ng-repeat指令要点 1,基本格式,这里不作过多说明,需要的话查看文档 <div ng-repeat="item in someCollection [| someFilter: ...
- 通过tarball形式安装HBASE Cluster(CDH5.0.2)——Hadoop NameNode HA 切换引起的Hbase错误,以及Hbase如何基于NameNode的HA进行配置
通过tarball形式安装HBASE Cluster(CDH5.0.2)——Hadoop NameNode HA 切换引起的Hbase错误,以及Hbase如何基于NameNode的HA进行配置 配置H ...
- 基于Java对图片进行二值化处理
一直以来对Java的图形处理能力表无力,但好像又不是那么一回事,之前用PHP做过一些应用,涉及到验证码的识别,其中有个图片二值化的步骤,今天换成Java来实现下 在java的扩展包javax.imag ...
- [转]java的(PO,VO,TO,BO,DAO,POJO)类名包名解释
java的(PO,VO,TO,BO,DAO,POJO)类名包名解释 2015-04-28 20:11 by Loull, 18 阅读, 0 评论, 收藏, 编辑 VO:值对象.视图对象 PO:持久对象 ...
- koa2使用注意点总结
post请求,ajax传入的参数获取的时候为ctx.request.body get请求,ajax传入参数获取的时候为ctx.request.query.参数名 koa-csrf可以设置什么请求的时候 ...
- python中的List 和 Tuple
#-*- coding:UTF-8 -*- classmates=["Michael","Bob","Tracy"] print(class ...