字典中的鍵使用時必須滿足一下兩個條件:
1、每個鍵只能對應一個項,也就是說,一鍵對應多個值時不允許的(列表、元組和其他字典的容器對象除外)。當有鍵發生沖突時(即字典鍵重復賦值),取最後的賦值。
>>> myuniversity_dict = {'name':'yuanyuan', 'age':18, 'age':19, 'age':20, 'schoolname':Chengdu, 'schoolname':Xinxiang}
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'Chengdu' is not defined
>>> myuniversity_dict = {'name':'yuanyuan', 'age':18, 'age':19, 'age':20, 'schoolname':'Chengdu', 'schoolname':'Xinxiang'}
>>> myuniversity_dict
{'age': 20, 'name': 'yuanyuan', 'schoolname': 'Xinxiang'}
>>>
2、鍵必須是可哈希的,像列表和字典這樣的可變類型,由於他們是不可哈希的,所以不能作為字典的鍵。
為什麼呢?—— 解釋器調用哈希函數,根據字典中鍵的值來計算存儲你的數據的位置。如果鍵是可變對象,可以對鍵本身進行修改,那麼當鍵發生變化時,哈希函數會映射到不同的地址來存儲數據,這樣哈希函數就不可能可靠地存儲或獲取相關的數據; 選擇可哈希鍵的原因就是他們的值不能被改變。摘抄python 核心編程(第二版)的一個實例如下:
#!/usr/bin/env python
db = {}
def newuser():
prompt = 'login desired: '
while True:
name = raw_input(prompt)
if db.has_key(name):
prompt = 'name taken, try another\n'
continue
else:
break
pwd = raw_input('passwd: ')
db[name] = pwd
def olduser():
name = raw_input('login: ')
pwd = raw_input('passwd: ')
passwd = db.get(name)
if passwd == pwd:
print 'welcome back', name
else:
print 'login incorrect'
def showmenu():
prompt = """
(N)ew User Login
(E)xisting User Login
(Q)uit
Enter choice:"""
done = False
while not done:
chosen = False
while not chosen:
try:
choice = raw_input(prompt).strip()[0].lower()
except:
choice = 'q'
print '\nYou picked: [%s]' % choice
if choice not in 'neq':
print 'invalid option, try again'
else:
chosen = True
if choice == 'q':done = True
if choice == 'n':newuser()
if choice == 'e':olduser()
if __name__ == '__main__':
showmenu()
運行結果:
[root@localhost src]# python usrpw.py
(N)ew User Login
(E)xisting User Login
(Q)uit
Enter choice:n
You picked: [n]
login desired: root
passwd: 1
(N)ew User Login
(E)xisting User Login
(Q)uit
Enter choice:n
You picked: [n]
login desired: root
name taken, try another
OpenCV官方教程中文版(For Python) PDF http://www.linuxidc.com/Linux/2015-08/121400.htm
Ubuntu Linux下安裝OpenCV2.4.1所需包 http://www.linuxidc.com/Linux/2012-08/68184.htm
Ubuntu 12.04 安裝 OpenCV2.4.2 http://www.linuxidc.com/Linux/2012-09/70158.htm
CentOS下OpenCV無法讀取視頻文件 http://www.linuxidc.com/Linux/2011-07/39295.htm
Ubuntu 12.04下安裝OpenCV 2.4.5總結 http://www.linuxidc.com/Linux/2013-06/86704.htm
Ubuntu 10.04中安裝OpenCv2.1九步曲 http://www.linuxidc.com/Linux/2010-09/28678.htm
基於QT和OpenCV的人臉識別系統 http://www.linuxidc.com/Linux/2011-11/47806.htm
[翻譯]Ubuntu 14.04, 13.10 下安裝 OpenCV 2.4.9 http://www.linuxidc.com/Linux/2014-12/110045.htm
OpenCV的詳細介紹:請點這裡
OpenCV的下載地址:請點這裡