Python字典排序 sort()、reversed()、sorted()、cmp()

廖雪峰讲sorted的链接

 

深入Python(1): 字典排序 关于sort()、reversed()、sorted()、cmp()等

2014年05月08日 11:11:08 文宇肃然 阅读数:3982更多

个人分类: Python

一、最不沾边的cmp()

cmp(xy)

Compare the two objects x and y and return an integer according to the outcome. The return value is negative if x < y, zero if x == y and strictly positive if x > y.

 

如:

str1 = 'abc'
str2 = 'lmn'
str3 = 'xyz'
print cmp(str1,str2)    #-1
print cmp(str3,str1)    #1
print cmp(str2,'lmn')   #0


Python核心编程2貌似有错误。

 

二、Python的排序

1、reversed()

这个很好理解,reversed英文意思就是:adj. 颠倒的;相反的;(判决等)撤销的

print list(reversed(['dream','a','have','I']))
#['I', 'have', 'a', 'dream']

2、让人糊涂的sort()与sorted()

英语中,sort是

  • vt. 将…分类;将…排序;挑选出某物
  • n.种类

英语中,sorted是

  • adj. 分类的;分选的;挑选的
  • v. 分类(sort的过去分词)

在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(可选参数) cmpkey, 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:http://hi.baidu.com/beynvrvbprbbklq/item/e6304e207602993295f62be5

推荐阅读2:http://www.cnblogs.com/kaituorensheng/archive/2012/08/07/2627386.html

下文内容部分来自以上推荐。

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

 

 

 

python中sort、sorted高级排序技巧

2017年02月22日 20:14:15 CrazyVertigo 阅读数:4683 标签: python 更多

个人分类: Python笔记

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hduxiejun/article/details/56495729

在python中对list进行排序有两种方法:

1.用List的成员函数sort进行排序 
2.用built-in函数sorted进行排序 
sorted与sort除了一个是序列作为参数,一个是序列调用该函数,其他参数几乎完全一致,下面逐一来介绍其用法及效果:

sort说明

help(list.sort) 
Help on method_descriptor: 
sort(…) 
L.sort(cmp=None, key=None, reverse=False) – stable sort IN PLACE
cmp(x, y) -> -1, 0, 1

sorted说明

help(sorted) 
Help on built-in function sorted in module builtin
sorted(…) 
sorted(iterable, cmp=None, key=None, reverse=False) –> new sorted list

iterable:是可迭代类型; 
cmp:用于比较的函数,比较什么由key决定,有默认值,迭代集合中的一项; 
key:用列表元素的某个属性和函数进行作为关键字,有默认值,迭代集合中的一项; 
reverse:排序规则. reverse = True 或者 reverse = False,有默认值。

注;一般来说,cmp和key可以使用lambda表达式。

sort()与sorted()的不同在于,sort是在原位重新排列列表,而sorted()是产生一个新的列表。

Sorting basic:

>>> print sorted([5, 2, 3, 1, 4])
[1, 2, 3, 4, 5]

>>> L = [5, 2, 3, 1, 4]
>>> L.sort()
>>> print L
[1, 2, 3, 4, 5]

Sorting  cmp:
>>>L = [('b',2),('a',1),('c',3),('d',4)]
>>>print sorted(L, cmp=lambda x,y:cmp(x[1],y[1]))
[('a', 1), ('b', 2), ('c', 3), ('d', 4)]

Sorting  keys:
>>>L = [('b',2),('a',1),('c',3),('d',4)]
>>>print sorted(L, key=lambda x:x[1]))
[('a', 1), ('b', 2), ('c', 3), ('d', 4)]
Sorting  reverse:

>>> print sorted([5, 2, 3, 1, 4], reverse=True)
[5, 4, 3, 2, 1]

>>> print sorted([5, 2, 3, 1, 4], reverse=False)
[1, 2, 3, 4, 5]

注:效率key>cmp(key比cmp快)

在Sorting Keys中:我们看到,此时排序过的L是仅仅按照第二个关键字来排的,如果我们想用第二个关键字 
排过序后再用第一个关键字进行排序呢?

L = [(‘d’,2),(‘a’,4),(‘b’,3),(‘c’,2)] 
print sorted(L, key=lambda x:(x[1],x[0])) 
[(‘c’, 2), (‘d’, 2), (‘b’, 3), (‘a’, 4)]

字典

1.sorted函数按key值对字典排序

>>>d={'A':3,'C':1,'B':2}
>>>sorted(d.keys())
['A', 'B', 'C']
>>>

直接使用sorted(d.keys())就能按key值对字典排序,这里是按照顺序对key值排序的,如果想按照倒序排序的话,则只要将reverse置为true即可。

2.sorted函数按value值对字典排序

要对字典的value排序则需要用到key参数,在这里主要提供一种使用lambda表达式的方法,如下:

>>>d={'A':3,'C':1,'B':2}
>>>sorted(d.items(),key=lambda item:item[1])

这里的d.items()实际上是将d转换为可迭代对象,迭代对象的元素为[(‘A’, 3), (‘C’, 1), (‘B’, 2)],items()方法将字典的元素转化为了元组,而这里key参数对应的lambda表达式的意思则是选取元组中的第二个元素作为比较参数(如果写作key=lambda item:item[0]的话则是选取第一个元素作为比较对象,也就是key值作为比较对象。lambda x:y中x表示输出参数,y表示lambda函数的返回值),所以采用这种方法可以对字典的value进行排序。注意排序后的返回值是一个list,而原字典中的名值对被转换为了list中的元组。

3.实战练习

设有n个正整数,将他们连接成一排,组成一个最大的多位整数. 
例如:3个整数13,312,343,连成的最大整数为:34331213 
又如:4个整数7,13,4,246连接成的最大整数为7424613 
现在给你一个正整数列表L,请你输出用这些正整数能够拼接成的最大整数。 
note:测试数据已于2014年11月13日更新,以前通过的代码不一定能够再次通过。

运用sorted代码如下:

maxlen = len(str(max(L)))
b = [{'old':str(x),'new':str(x)+str(x)[-1]*(maxlen-len(str(x)))}  for x in L]
#print b
tmpret = [value["old"] for value in sorted(b,key=lambda s:s["new"],reverse=True)]
print(''.join(tmpret))

输出结果:

b= [{‘new’: ‘777’, ‘old’: ‘7’}, {‘new’: ‘133’, ‘old’: ‘13’}, {‘new’: ‘444’, ‘old’: ‘4’}, {‘new’: ‘246’, ‘old’: ‘246’}] 
7424613

b中包含了多个字典,如何对每个字典中的‘new’进行排序呢?

参考网址: 
http://www.cnblogs.com/65702708/archive/2010/09/14/1826362.html 
http://www.jb51.net/article/57678.htm

http://blog.csdn.net/tangtanghao511/article/details/47810729

特别推荐: 
http://www.cnblogs.com/yushuo1990/p/5880041.html

  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值