亚洲av成人无遮挡网站在线观看,少妇性bbb搡bbb爽爽爽,亚洲av日韩精品久久久久久,兔费看少妇性l交大片免费,无码少妇一区二区三区

  免費注冊 查看新帖 |

Chinaunix

  平臺 論壇 博客 文庫
最近訪問板塊 發(fā)新帖
查看: 3096 | 回復: 0
打印 上一主題 下一主題

Python 語法之字典 [復制鏈接]

論壇徽章:
0
跳轉(zhuǎn)到指定樓層
1 [收藏(0)] [報告]
發(fā)表于 2009-10-21 10:06 |只看該作者 |倒序瀏覽


  Normal
  0
  
  
  
  7.8 磅
  0
  2
  
  false
  false
  false
  
  EN-US
  ZH-CN
  X-NONE
  
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
  
  
   
   
   
   
   
   
   
   
   
   
   
  

  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  

/* Style Definitions */
table.MsoNormalTable
        {mso-style-name:普通表格;
        mso-tstyle-rowband-size:0;
        mso-tstyle-colband-size:0;
        mso-style-noshow:yes;
        mso-style-priority:99;
        mso-style-qformat:yes;
        mso-style-parent:"";
        mso-padding-alt:0cm 5.4pt 0cm 5.4pt;
        mso-para-margin:0cm;
        mso-para-margin-bottom:.0001pt;
        mso-pagination:widow-orphan;
        font-size:10.5pt;
        mso-bidi-font-size:11.0pt;
        font-family:"Calibri","sans-serif";
        mso-ascii-font-family:Calibri;
        mso-ascii-theme-font:minor-latin;
        mso-hansi-font-family:Calibri;
        mso-hansi-theme-font:minor-latin;
        mso-font-kerning:1.0pt;}
File information
2009-10-21
磁針石:xurongzhong#gmail.com
博客:
oychw.cublog.cn
參考資料:
《Python Essential Reference 4th
Edition 2009》
《beginning python from novice to
professional second edition 2008》


*特點:無序,是唯一內(nèi)置的映射類型。多用于實現(xiàn)哈希表或者關聯(lián)數(shù)組。
key具有唯一性,可以使用固定長度的對象,不能使用列表、字典和包含可變長度類型的元組。訪問形式:m[k],k是key。如果找不到,報錯:KeyError。
方法和操作如下:


  
  項目
  
  
  功能
  


  
  len(m)
  
  
   Key的長度
  


  
  m[k]
  
  
   
  


  
  m[k]=x
  
  
   
  


  
  del m[k]
  
  
   
  


  
  k in m
  
  
   有沒有k的key
  


  
  m.clear()
  
  
   
  


  
  m.copy()
  
  
   
  


  
  m.fromkeys(s [,value])
  
  
   
  


  
  m.get(k [,v])
  
  
   
  


  
  m.has_key(k)
  
  
   
  


  
  m.items()
  
  
   
  


  
  m.keys()
  
  
   
  


  
  m.pop(k [,default])
  
  
   
  


  
  m.popitem()
  
  
   
  


  
  m.setdefault(k [, v])
  
  
   
  


  
  m.update(b)
  
  
   
  


  
  m.values()
  
  
   
  


*構建字典

字典舉例:
phonebook = {'Alice': '2341', 'Beth':
'9102', 'Cecil': '3258'}
函數(shù)Dict可以從其他映射或者序列構建字典
>>> items = [('name', 'Gumby'),
('age', 42)]
>>> d = dict(items)
>>> d
{'age': 42, 'name': 'Gumby'}
>>> d['name']
'Gumby'

       也可以使用參數(shù)的方法:
>>> d = dict(name='Gumby', age=42)
>>> d
{'age': 42, 'name': 'Gumby'}
初始化空字典:
>>> x = {}
>>> x[42] = 'Foobar'
>>> x
{42: 'Foobar'}

*格式化輸出:
>>> phonebook
{'Beth': '9102', 'Alice': '2341', 'Cecil':
'3258'}
>>> "Cecil's phone number is
%(Cecil)s." % phonebook
"Cecil's phone number is 3258."


>>>
template = '''
%(title)s
%(title)s
%(text)s
'''
>>>
data = {'title': 'My Home Page', 'text': 'Welcome to my home page!'}
>>>
print template % data
My
Home Page
My
Home Page
Welcome
to my home page!

另外string.Template 類也很適合這種應用。

*字典方法:
-*清除:clear
       下面例子展示clear和把字典置空字典的區(qū)別:
>>> x = {}
>>> y = x
>>> x['key'] = 'value'
>>> y
{'key': 'value'}
>>> x = {}
>>> y
{'key': 'value'}


>>> x = {}
>>> y = x
>>> x['key'] = 'value'
>>> y
{'key': 'value'}
>>> x.clear()
>>> y
{}


-*復制:copy

>>> x = {'username': 'admin',
'machines': ['foo', 'bar', 'baz']}
>>> y = x.copy()
>>> y['username'] = 'mlh'
>>> y['machines'].remove('bar')
>>> y
{'username': 'mlh', 'machines': ['foo',
'baz']}
>>> x
{'username': 'admin', 'machines': ['foo',
'baz']}

       淺拷貝的元素指向原有元素,所以改變原有的可變元素,新的也會受影響,反之亦然。換種說法,對元素進行替換,不會對新老都產(chǎn)生影響,但是修改則會有影響。

>>> from copy import deepcopy
>>> d = {}
>>> d['names'] = ['Alfred',
'Bertrand']
>>> c = d.copy()
>>> dc = deepcopy(d)
>>> d['names'].append('Clive')
>>> c
{'names': ['Alfred', 'Bertrand', 'Clive']}
>>> dc
{'names': ['Alfred', 'Bertrand']}

-*復制key:fromkeys
>>> {}.fromkeys(['name', 'age'])
{'age': None, 'name': None}
       也可以用dict代替{}
>>> dict.fromkeys(['name', 'age'])
{'age': None, 'name': None}
        設置其他默認值:
>>> dict.fromkeys(['name', 'age'],
'(unknown)')
{'age': '(unknown)', 'name': '(unknown)'}


-*獲。篻et

>>> d = {}
>>> print d['name']
Traceback (most recent call last):
File "", line 1, in
?
KeyError: 'name'
>>> print d.get('name')
None
也可以用其他字符替代None

>>> d.get('name', 'N/A')
'N/A'

-*has_key:是否有key
和k in d是等效的,Python 3.0將取消這個,建議不要使用
>>> d = {}
>>> d.has_key('name')
False
>>> d['name'] = 'Eric'
>>> d.has_key('name')
True

-*列出值:items and
iteritems
>>> d = {'title': 'Python Web
Site', 'url': 'http://www.python.org', 'spam': 0}
>>> d.items()
[('url', 'http://www.python.org'), ('spam',
0), ('title', 'Python Web Site')]

>>> it = d.iteritems()
>>> it
>>> list(it) # Convert the
iterator to a list
[('url', 'http://www.python.org'), ('spam',
0), ('title', 'Python Web Site')]
       Iteritems生成迭代器,一般的情況下使用iteritems比iteritem更有效,尤其是循環(huán)的時候。
注:Python 3 items 返回的是迭代器

-*列出關鍵字:keys
and iterkeys
       后者是迭代器
根據(jù)key出棧:pop
>>> d = {'x': 1, 'y': 2}
>>> d.pop('x')
1
>>> d
{'y': 2}
-*出棧:popitem
>>>
d
{'url':
'http://www.python.org', 'spam': 0, 'title': 'Python Web Site'}
>>>
d.popitem()
('url',
'http://www.python.org')
>>>
d
{'spam':
0, 'title': 'Python Web Site'}
       出棧和列表和類似,但是沒有append。
-*setdefault:設置默認值。
>>>
d = {}
>>>
d.setdefault('name', 'N/A')
'N/A'
>>>
d
{'name':
'N/A'}
>>>
d['name'] = 'Gumby'
>>>
d.setdefault('name', 'N/A')
'Gumby'
>>>
d
{'name':
'Gumby'}
       默認值的默認值為None。
>>>
d = {}
>>>
print d.setdefault('name')
None
>>>
d
{'name':
None}

-*更新:update
>>> d = {
'title': 'Python Web Site',
'url': 'http://www.python.org',
'changed': 'Mar 14 22:09:15 MET 2008'
}
>>> x = {'title': 'Python Language
Website'}
>>> d.update(x)
>>> d
{'url': 'http://www.python.org', 'changed':
'Mar 14 22:09:15 MET 2008', 'title':
'Python Language Website'}


-*取值:values and
itervalues

>>> d = {}
>>> d[1] = 1
>>> d[2] = 2
>>> d[3] = 3
>>> d[4] = 1
>>> d.values()
[1, 2, 3, 1]


*實例:
存儲個人的電話和地址的腳本:

# A simple
database

# A
dictionary with person names as keys. Each person is represented as
#
another dictionary with the keys 'phone' and 'addr' referring to their phone
# number
and address, respectively.

people =
{

    'Alice': {
        'phone': '2341',
        'addr': 'Foo drive 23'
    },

    'Beth': {
        'phone': '9102',
        'addr': 'Bar street 42'
    },

    'Cecil': {
        'phone': '3158',
        'addr': 'Baz avenue 90'
    }

}

#
Descriptive labels for the phone number and address. These will be used
# when
printing the output.
labels =
{
    'phone': 'phone number',
    'addr': 'address'
}

name =
raw_input('Name: ')

# Are we
looking for a phone number or an address?
request
= raw_input('Phone number (p) or address (a)? ')

# Use the
correct key:
if
request == 'p': key = 'phone'
if
request == 'a': key = 'addr'

# Only
try to print information if the name is a valid key in
# our
dictionary:
if name
in people: print "%s's %s is %s." % \
(name, labels[key], people[name][key])


將上述例子改為getkey

# A simple database

# A dictionary with person names as keys.
Each person is represented as
# another dictionary with the keys 'phone'
and 'addr' referring to their phone
# number and address, respectively.

people = {

   
'Alice': {
      
'phone': '2341',
      
'addr': 'Foo drive 23'
    },

   
'Beth': {
      
'phone': '9102',
      
'addr': 'Bar street 42'
    },

   
'Cecil': {
      
'phone': '3158',
      
'addr': 'Baz avenue 90'
    }

}


labels = {
   
'phone': 'phone number',
   
'addr': 'address'
}

name = raw_input('Name: ')

# Are we looking for a phone number or an
address?
request = raw_input('Phone number (p) or
address (a)? ')

# Use the correct key:
key = request # In case the request is
neither 'p' nor 'a'
if request == 'p': key = 'phone'
if request == 'a': key = 'addr'

# Use get to provide default values:
person = people.get(name, {})
label = labels.get(key, key)
result = person.get(key, 'not available')

print "%s's %s is %s." % (name,
label, result)


               
               
               

本文來自ChinaUnix博客,如果查看原文請點:http://blog.chinaunix.net/u/21908/showart_2074565.html
您需要登錄后才可以回帖 登錄 | 注冊

本版積分規(guī)則 發(fā)表回復

  

北京盛拓優(yōu)訊信息技術有限公司. 版權所有 京ICP備16024965號-6 北京市公安局海淀分局網(wǎng)監(jiān)中心備案編號:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年舉報專區(qū)
中國互聯(lián)網(wǎng)協(xié)會會員  聯(lián)系我們:huangweiwei@itpub.net
感謝所有關心和支持過ChinaUnix的朋友們 轉(zhuǎn)載本站內(nèi)容請注明原作者名及出處

清除 Cookies - ChinaUnix - Archiver - WAP - TOP