python字典的遍曆與排序__python

來源:互聯網
上載者:User

字典的遍曆:

首先:

items():

功能:以列表的形式返回字典索引值對

eg:

dict_={"a":2,"b":3,"c":6}

dict_.items()

>>>[('a',2),('b',3),('c',6)]

iteritems():

功能:以迭代器對象返回字典索引值對

# -*- 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:

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]就是按字典的鍵排序)

sorted(dict.iteritems(),key=lambda dict:dict[1],reverse=True)

解釋說明:

dict.iteritems()得到[(鍵,索引值),(鍵,索引值),(鍵,索引值)...]的列表。然後用sorted方法,通過key這個參數指定排序是按照索引值,也就是第一個元素d[1]的值來排序。reverse=True表示需要翻轉的(即降序排序),預設是升序排序。


函數lambda與函數iteritems()

lambda:

功能:建立匿名函數

eg:

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():

功能:以迭代器對象返回字典索引值對


# -*- 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"


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.