1. 程式人生 > >深入Python(1): 字典排序 關於sort()、reversed()、sorted()、cmp()等

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

一、最不沾邊的cmp()

cmp(x, y)

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(可選引數) 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: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