欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python中字典創(chuàng)建、遍歷、添加等實(shí)用操作技巧合集

 更新時(shí)間:2015年06月02日 15:42:42   投稿:junjie  
這篇文章主要介紹了Python中字典創(chuàng)建、遍歷、添加等實(shí)用操作技巧合集,本文講解了字典中常見(jiàn)方法列表、創(chuàng)建字典的五種方法、字典中鍵值遍歷方法等內(nèi)容,需要的朋友可以參考下

字段是Python是字典中唯一的鍵-值類型,是Python中非常重要的數(shù)據(jù)結(jié)構(gòu),因其用哈希的方式存儲(chǔ)數(shù)據(jù),其復(fù)雜度為O(1),速度非??臁O旅媪谐鲎值涞某S玫挠猛?
一、字典中常見(jiàn)方法列表

復(fù)制代碼 代碼如下:

#方法                                  #描述 
------------------------------------------------------------------------------------------------- 
D.clear()                              #移除D中的所有項(xiàng) 
D.copy()                               #返回D的副本 
D.fromkeys(seq[,val])                  #返回從seq中獲得的鍵和被設(shè)置為val的值的字典??勺鲱惙椒ㄕ{(diào)用 
D.get(key[,default])                   #如果D[key]存在,將其返回;否則返回給定的默認(rèn)值None 
D.has_key(key)                         #檢查D是否有給定鍵key 
D.items()                              #返回表示D項(xiàng)的(鍵,值)對(duì)列表 
D.iteritems()                          #從D.items()返回的(鍵,值)對(duì)中返回一個(gè)可迭代的對(duì)象 
D.iterkeys()                           #從D的鍵中返回一個(gè)可迭代對(duì)象 
D.itervalues()                         #從D的值中返回一個(gè)可迭代對(duì)象 
D.keys()                               #返回D鍵的列表 
D.pop(key[,d])                         #移除并且返回對(duì)應(yīng)給定鍵key或給定的默認(rèn)值D的值 
D.popitem()                            #從D中移除任意一項(xiàng),并將其作為(鍵,值)對(duì)返回 
D.setdefault(key[,default])            #如果D[key]存在則將其返回;否則返回默認(rèn)值None 
D.update(other)                        #將other中的每一項(xiàng)加入到D中。 
D.values()                             #返回D中值的列表

二、創(chuàng)建字典的五種方法

方法一: 常規(guī)方法   

復(fù)制代碼 代碼如下:

# 如果事先能拼出整個(gè)字典,則此方法比較方便
>>> D1 = {'name':'Bob','age':40} 

方法二: 動(dòng)態(tài)創(chuàng)建
復(fù)制代碼 代碼如下:
                 
# 如果需要?jiǎng)討B(tài)地建立字典的一個(gè)字段,則此方法比較方便
>>> D2 = {} 
>>> D2['name'] = 'Bob' 
>>> D2['age']  =  40 
>>> D2 
{'age': 40, 'name': 'Bob'}

方法三:  dict--關(guān)鍵字形式      
復(fù)制代碼 代碼如下:

# 代碼比較少,但鍵必須為字符串型。常用于函數(shù)賦值
>>> D3 = dict(name='Bob',age=45) 
>>> D3 
{'age': 45, 'name': 'Bob'}

方法四: dict--鍵值序列

復(fù)制代碼 代碼如下:

# 如果需要將鍵值逐步建成序列,則此方式比較有用,常與zip函數(shù)一起使用
>>> D4 = dict([('name','Bob'),('age',40)]) 
>>> D4 
{'age': 40, 'name': 'Bob'}


復(fù)制代碼 代碼如下:

>>> D = dict(zip(('name','bob'),('age',40))) 
>>> D 
{'bob': 40, 'name': 'age'} 

方法五: dict--fromkeys方法# 如果鍵的值都相同的話,用這種方式比較好,并可以用fromkeys來(lái)初始化
復(fù)制代碼 代碼如下:

>>> D5 = dict.fromkeys(['A','B'],0) 
>>> D5 
{'A': 0, 'B': 0} 

如果鍵的值沒(méi)提供的話,默認(rèn)為None
復(fù)制代碼 代碼如下:

>>> D3 = dict.fromkeys(['A','B']) 
>>> D3 
{'A': None, 'B': None} 

三、字典中鍵值遍歷方法

復(fù)制代碼 代碼如下:

>>> D = {'x':1, 'y':2, 'z':3}          # 方法一 
>>> for key in D: 
    print key, '=>', D[key]   
y => 2 
x => 1 
z => 3 
>>> for key, value in D.items():       # 方法二 
    print key, '=>', value    
y => 2 
x => 1 
z => 3 
 
>>> for key in D.iterkeys():           # 方法三 
    print key, '=>', D[key]   
y => 2 
x => 1 
z => 3 
>>> for value in D.values():           # 方法四 
    print value  



>>> for key, value in D.iteritems():   # 方法五 
    print key, '=>', value 
     
y => 2 
x => 1 
z => 3 

Note:用D.iteritems(), D.iterkeys()的方法要比沒(méi)有iter的快的多。

四、字典的常用用途之一代替switch

在C/C++/Java語(yǔ)言中,有個(gè)很方便的函數(shù)switch,比如:

復(fù)制代碼 代碼如下:

public class test { 
     
    public static void main(String[] args) { 
        String s = "C"; 
        switch (s){ 
        case "A":  
            System.out.println("A"); 
            break; 
        case "B": 
            System.out.println("B"); 
            break; 
        case "C": 
            System.out.println("C"); 
            break; 
        default: 
            System.out.println("D"); 
        } 
    } 

在Python中要實(shí)現(xiàn)同樣的功能,
方法一,就是用if, else語(yǔ)句來(lái)實(shí)現(xiàn),比如:

復(fù)制代碼 代碼如下:

from __future__ import division 
 
def add(x, y): 
    return x + y 
 
def sub(x, y): 
    return x - y 
 
def mul(x, y): 
    return x * y 
 
def div(x, y): 
    return x / y 
 
def operator(x, y, sep='+'): 
    if   sep == '+': print add(x, y) 
    elif sep == '-': print sub(x, y) 
    elif sep == '*': print mul(x, y) 
    elif sep == '/': print div(x, y) 
    else: print 'Something Wrong' 
 
print __name__ 
  
if __name__ == '__main__': 
    x = int(raw_input("Enter the 1st number: ")) 
    y = int(raw_input("Enter the 2nd number: ")) 
    s = raw_input("Enter operation here(+ - * /): ") 
    operator(x, y, s) 

方法二,用字典來(lái)巧妙實(shí)現(xiàn)同樣的switch的功能,比如:

復(fù)制代碼 代碼如下:

#coding=gbk 
 
from __future__ import division 
 
x = int(raw_input("Enter the 1st number: ")) 
y = int(raw_input("Enter the 2nd number: ")) 
 
def operator(o): 
    dict_oper = { 
        '+': lambda x, y: x + y, 
        '-': lambda x, y: x - y, 
        '*': lambda x, y: x * y, 
        '/': lambda x, y: x / y} 
    return dict_oper.get(o)(x, y) 
  
if __name__ == '__main__':   
    o = raw_input("Enter operation here(+ - * /): ") 
    print operator(o) 

相關(guān)文章

最新評(píng)論