国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 編程 > Python > 正文

python中的字典使用分享

2019-11-25 16:37:37
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

字典中的鍵使用時(shí)必須滿(mǎn)足一下兩個(gè)條件:

1、每個(gè)鍵只能對(duì)應(yīng)一個(gè)項(xiàng),也就是說(shuō),一鍵對(duì)應(yīng)多個(gè)值時(shí)不允許的(列表、元組和其他字典的容器對(duì)象除外)。當(dāng)有鍵發(fā)生沖突時(shí)(即字典鍵重復(fù)賦值),取最后的賦值。

復(fù)制代碼 代碼如下:
>>> 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、鍵必須是可哈希的,像列表和字典這樣的可變類(lèi)型,由于他們是不可哈希的,所以不能作為字典的鍵。

為什么呢?―― 解釋器調(diào)用哈希函數(shù),根據(jù)字典中鍵的值來(lái)計(jì)算存儲(chǔ)你的數(shù)據(jù)的位置。如果鍵是可變對(duì)象,可以對(duì)鍵本身進(jìn)行修改,那么當(dāng)鍵發(fā)生變化時(shí),哈希函數(shù)會(huì)映射到不同的地址來(lái)存儲(chǔ)數(shù)據(jù),這樣哈希函數(shù)就不可能可靠地存儲(chǔ)或獲取相關(guān)的數(shù)據(jù); 選擇可哈希鍵的原因就是他們的值不能被改變。摘抄python 核心編程(第二版)的一個(gè)實(shí)例如下:

#!/usr/bin/env pythondb = {}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] = pwddef 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)uitEnter 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()

運(yùn)行結(jié)果:

[root@localhost src]# python usrpw.py (N)ew User Login(E)xisting User Login(Q)uitEnter choice:nYou picked: [n]login desired: rootpasswd: 1(N)ew User Login(E)xisting User Login(Q)uitEnter choice:nYou picked: [n]login desired: rootname taken, try another

發(fā)表評(píng)論 共有條評(píng)論
用戶(hù)名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 岳西县| 固始县| 茌平县| 华蓥市| 聂拉木县| 伽师县| 南安市| 砚山县| 库伦旗| 新野县| 丹阳市| 博客| 察哈| 东乡族自治县| 阳曲县| 漯河市| 南通市| 淅川县| 沛县| 灌阳县| 平乐县| 札达县| 上饶县| 安阳市| 石楼县| 塔河县| 鹿泉市| 五台县| 万年县| 南江县| 汉中市| 盐边县| 简阳市| 兴山县| 离岛区| 东乡族自治县| 南华县| 昌图县| 大竹县| 仙游县| 灌南县|