本文實例講述了Python實現字典的遍歷與排序功能。分享給大家供大家參考,具體如下:
字典的遍歷:
首先:
items():
功能:以列表的形式返回字典鍵值對
eg:
1
2
3
|
dict_ = { "a" : 2 , "b" : 3 , "c" : 6 } dict_.items() >>>[( 'a' , 2 ),( 'b' , 3 ),( 'c' , 6 )] |
iteritems():
功能:以迭代器對象返回字典鍵值對
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
# -*- coding: cp936 -*- dict1 = { 'a' : 1 , 'b' : 2 , 'c' : 3 } #第一種: for d in dict1: print "%s:%d" % (d,dict1[d]) print #第二種: for k,v in dict1.items(): print "%s:%d" % (k,v) print #第三種: for k,v in dict1.iteritems(): print "%s:%d" % (k,v) print #第四種: for k in dict1.iterkeys(): print "%s:%d" % (k,dict1[k]) print #第五種: for v in dict1.itervalues(): print v print #第六種: for k,v in zip (dict1.iterkeys(),dict1.itervalues()): print "%s:%d" % (k,v) print |
zip()
函數可以把列表合并,并創建一個元祖對的列表。
eg:
1
2
3
4
|
list1 = [ 1 , 2 , 3 ] list2 = [ 4 , 5 , 6 ] zip (a,b) >>>[( 1 , 4 ),( 2 , 5 ),( 3 , 6 )] |
zip()
函數參數可以是任何類型的序列,也可以有兩個以上的參數,當傳入參數的長度不同時,zip自動以最短序列長度為準進行截取,獲得元祖。
字典的排序:
首先:
函數sorted(dic,value,reverse)
過程:第一個參數傳遞給第二個參數“鍵-鍵值”,第二個參數取出其中的鍵[0]或鍵值[1]
dic為比較函數,value為排序對象(鍵或者鍵值)
reverse注明升序排序或是降序排序,值有true-降序和false-升序(默認值)
eg:按字典的鍵值排序(把dict[1]換成dict[0]就是按字典的鍵排序)
1
|
sorted ( dict .iteritems(),key = lambda dict : dict [ 1 ],reverse = True ) |
解釋說明:
dict.iteritems()
得到[(鍵,鍵值),(鍵,鍵值),(鍵,鍵值)...]的列表。然后用sorted方法,通過key這個參數指定排序是按照鍵值,也就是第一個元素d[1]的值來排序。reverse=True表示需要翻轉的(即降序排序),默認是升序排序。
函數lambda與函數iteritems()
lambda:
功能:創建匿名函數
eg:
1
2
3
4
5
6
|
fun_1 = lambda a:a + 1 print fun_1( 1 ) >>> 2 fun_2 = lambda a,b:a + 2 * b fun_2( 1 , 1 ) >>> 3 |
iteritems():
功能:以迭代器對象返回字典鍵值對
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
# -*- coding: cp936 -*- print "按字典鍵值進行排序" dict1 = { 'a' : 3 , 'c' : 1 , 'b' : 2 } #升序: dict_a = sorted (dict1.iteritems(),key = lambda dict1:dict1[ 1 ],reverse = False ) #降序排序reverse=True ,該參數可省,默認為False。 或者dict_a.reverse() print dict_a, "\n" #降序: dict2 = { 'a' : 3 , 'c' : 1 , 'b' : 2 } dict_b = sorted (dict2.iteritems(),key = lambda dict2:dict2[ 1 ],reverse = True ) print dict_b, "\n" ############################################################## print "按字典鍵進行排序" dict3 = { 'd' : 6 , 'e' : 5 , 'f' : 4 } #降序: dict_c = sorted (dict3.iteritems(),key = lambda dict3:dict3[ 0 ],reverse = True ) #降序排序reverse=True ,該參數可省,默認為False。 或者dict_a.reverse() print dict_c, "\n" #升序: dict4 = { 'd' : 6 , 'e' : 5 , 'f' : 4 } dict_d = sorted (dict4.iteritems(),key = lambda dict4:dict4[ 0 ]) #改為降序與上面同理 print dict_d, "\n" |
希望本文所述對大家Python程序設計有所幫助。
原文鏈接:http://blog.csdn.net/sgz_06_666666/article/details/53184198