http://www.cnblogs.com/BeginMan/p/3193081.html

一、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}, {'s
mall': 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的结构。

======================================

    1. #-*- encoding=utf-8 -*-
    2. import operator
    3. #按字典值排序(默认为升序)
    4. x = {1:2, 3:4, 4:3, 2:1, 0:0}
    5. sorted_x = sorted(x.iteritems(), key=operator.itemgetter(1))
    6. print sorted_x
    7. #[(0, 0), (2, 1), (1, 2), (4, 3), (3, 4)]
    8. #如果要降序排序,可以指定reverse=True
    9. sorted_x = sorted(x.iteritems(), key=operator.itemgetter(1), reverse=True)
    10. print sorted_x
    11. #[(3, 4), (4, 3), (1, 2), (2, 1), (0, 0)]
    12. #或者直接使用list的reverse方法将sorted_x顺序反转
    13. #sorted_x.reverse()
    14. #取代方法是,用lambda表达式
    15. sorted_x = sorted(x.iteritems(), key=lambda x : x[1])
    16. print sorted_x
    17. #[(0, 0), (2, 1), (1, 2), (4, 3), (3, 4)]
    18. sorted_x = sorted(x.iteritems(), key=lambda x : x[1], reverse=True)
    19. print sorted_x
    20. #[(3, 4), (4, 3), (1, 2), (2, 1), (0, 0)]
    21. #包含字典dict的列表list的排序方法与dict的排序类似,如下:
    22. x = [{'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}]
    23. sorted_x = sorted(x, key=operator.itemgetter('name'))
    24. print sorted_x
    25. #[{'age': 10, 'name': 'Bart'}, {'age': 39, 'name': 'Homer'}]
    26. sorted_x = sorted(x, key=operator.itemgetter('name'), reverse=True)
    27. print sorted_x
    28. #[{'age': 39, 'name': 'Homer'}, {'age': 10, 'name': 'Bart'}]
    29. sorted_x = sorted(x, key=lambda x : x['name'])
    30. print sorted_x
    31. #[{'age': 10, 'name': 'Bart'}, {'age': 39, 'name': 'Homer'}]
    32. sorted_x = sorted(x, key=lambda x : x['name'], reverse=True)
    33. print sorted_x
    34. #[{'age': 39, 'name': 'Homer'}, {'age': 10, 'name': 'Bart'}]

深入Python(1): 字典排序 关于sort()、reversed()、sorted()的更多相关文章

  1. Python中的排序方法sort(),sorted(),argsort()等

    python 列表排序方法sort.sorted技巧篇 转自https://www.cnblogs.com/whaben/p/6495702.html,学习参考. Python list内置sort( ...

  2. python 字典排序 关于sort()、reversed()、sorted()

    一.Python的排序 1.reversed() 这个很好理解,reversed英文意思就是:adj. 颠倒的:相反的:(判决等)撤销的 print list(reversed(['dream','a ...

  3. <转>python字典排序 关于sort()、reversed()、sorted()

    一.Python的排序 1.reversed() 这个很好理解,reversed英文意思就是:adj. 颠倒的:相反的:(判决等)撤销的 print list(reversed(['dream','a ...

  4. python中字典排序

    一.Python的排序 1.reversed() 这个很好理解,reversed英文意思就是:adj. 颠倒的:相反的:(判决等)撤销的 print list(reversed(['dream','a ...

  5. python中字典排序,列表中的字典排序

    python中字典排序,列表中的字典排序 一.使用python模块:operator import operator #首先要导入模块operator x = {1:2, 3:4, 4:3, 2:1, ...

  6. Python:如何排序(sort)

    一.前言 对Python的列表(list)有两个用于排序的方法: 一个是内建方法list.sort(),可以直接改变列表的内容: >>> list1 = [9,8,7,6,5] &g ...

  7. python 列表排序方法sort、sorted技巧篇

    Python list内置sort()方法用来排序,也可以用python内置的全局sorted()方法来对可迭代的序列排序生成新的序列. 1)排序基础 简单的升序排序是非常容易的.只需要调用sorte ...

  8. python 两种排序方法 sort() sorted()

    python中有两种排序方法,list内置sort()方法或者python内置的全局sorted()方法 区别为: sort()方法对list排序会修改list本身,不会返回新list.sort()只 ...

  9. [python学习] 语言基础—排序函数(sort()、sorted()、argsort()函数)

    python的内建排序函数有 sort.sorted两个. 1.基础的序列升序排序直接调用sorted()方法即可 ls = list([5, 2, 3, 1, 4]) new_ls = sorted ...

随机推荐

  1. 洛谷P2709 小B的询问

    题目描述 小B有一个序列,包含N个1~K之间的整数.他一共有M个询问,每个询问给定一个区间[L..R],求Sigma(c(i)^2)的值,其中i的值从1到K,其中c(i)表示数字i在[L..R]中的重 ...

  2. [转] Chrome - 浏览器跨域访问设置(附:新老版本两种设置方法)

    [From] http://www.hangge.com/blog/cache/detail_1703.html 在进行前后分离的 webapp 开发,或者 H5 移动 App 开发时,我们会使用 P ...

  3. 在Eclipse中调试web项目

    由于现在的公司用的是Eclipse开发web项目而且不安装MyEclipse插件,没有myclipse插件就不能在Eclipse中配置web服务器,所以也就不好对web项目进行调试.下面的方法就可以让 ...

  4. PIE SDK地图鹰眼图

    鹰眼图,是GIS的一个基本功能,在鹰眼图上可以像从空中俯视一样查看地图框中所显示的地图在整个图中的位置,是对全局地图的一种概述表达,能够起到很好的空间提示和导航的作用.网上有很多Arcengine 二 ...

  5. Linux-Xshell5

    Linux-Xshell5 1.下载 2.安装 3.新建会话(连接) 点击新建 需要知道要连接的 IP, 查看命令   ifconfig 配置 名称可以自己命名,主机写要连接的 IP,其他的不能改 输 ...

  6. 在Spark shell中基于HDFS文件系统进行wordcount交互式分析

    Spark是一个分布式内存计算框架,可部署在YARN或者MESOS管理的分布式系统中(Fully Distributed),也可以以Pseudo Distributed方式部署在单个机器上面,还可以以 ...

  7. 使用jxl读取excel内容,并转换成Json,用于Datagrid

    一.上传excel文件,得到InputStream,由InputStream得到Jxl中的Workbook,取出内容,存到二维数组中. 1.使用 Jquery Uploadify 插件(http:// ...

  8. C++ Memory System Part1: new和delete

    在深入探索自定义内存系统之前,我们需要了解一些基础的背景知识,这些知识点是我们接下来自定义内存系统的基础.所以第一部分,让我们来一起深入了解一下C++的new和delete家族,这其中有很多令人吃惊的 ...

  9. D3(v5) in TypeScript 坐标轴之 scaleBand用法

    在学习d3时候,发现在TS中实现D3的坐标轴中遇到一些错误,而这些错误却不会存在于js(因为ts的类型检查)写法中,因此做下笔记: import * as d3 from 'd3';import * ...

  10. 弹性布局学习-详解 align-items(四)

    目录 弹性布局学习-介绍(一)  弹性布局学习-详解 flex-direction[决定主轴的方向](二) 弹性布局学习-详解 justify-content(三) 弹性布局学习-详解 align-i ...