第7章
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了第7章相关的知识,希望对你有一定的参考价值。
7-1:
dict.update()
7-2:
当元组中只包括像数字和字符串这样的不可变参数时,可以作为字典中的键。对于不能用作字典键的对象类型,原因在于它们不是可哈希的,解释器调用哈希函数,根据字典中键的值来计算所存储数据的位置。如果键是可变对象,它的值可改变。如果键发生变化,哈希函数会映射到不同的地址来存储数据,如果这样的情况发生,哈希函数就不可能可靠地存储或获取相关的数据。
7-3:
(a)
adict = {‘a‘:1, ‘c‘:3, ‘q‘:123, ‘m‘:7} for key in sorted(adict): print key,
(b)
adict = {‘a‘:1, ‘c‘:3, ‘q‘:123, ‘m‘:7} for key in sorted(adict): print key, adict[key]
(c)
adict = {‘a‘:1, ‘c‘:3, ‘q‘:123, ‘m‘:7} values = adict.values() values.sort() print values for value in values: for key in adict: if adict[key] == value: print key, value break
7-4:
def list2dict(l1, l2): adict = {} for item in range(len(l1)): adict.update({l1[item]:l2[item]}) return adict
7-5:
(a)
1 #!/usr/bin/env python 2 3 import time 4 5 db = {} 6 7 def newuser(): 8 prompt = ‘login desired: ‘ 9 while True: 10 name = raw_input(prompt) 11 if db.has_key(name): 12 prompt = ‘name taken, try another: ‘ 13 continue 14 else: 15 break 16 pwd = raw_input(‘passed: ‘) 17 db[name] = [pwd, time.asctime()] 18 19 def olduser(): 20 print ‘Please enter your username and password‘ 21 name = raw_input(‘login: ‘) 22 pwd = raw_input(‘passed: ‘) 23 passwd = db.get(name)[0] 24 if passwd == pwd: 25 print ‘welcome back‘, name 26 if (int(time.asctime()[-13:-11]) - int(db[name][1][-13:-11])) <= 4: 27 print "You already logged in at:", db[name][1] 28 db[name][1] = time.asctime() 29 else: 30 print ‘login incorrect‘ 31 32 def showmenu(): 33 prompt = """ 34 (N)ew User login 35 (E)xisting User login 36 (Q)uit 37 38 Enter choice: """ 39 40 done = False 41 while not done: 42 43 chosen = False 44 while not chosen: 45 try: 46 choice = raw_input(prompt).strip()[0].lower() 47 except (EOFError, KeyboardInterrupt): 48 choice = ‘q‘ 49 print ‘\nYou picked: [%s]‘ % choice 50 if choice not in ‘neq‘: 51 print ‘invalid option, try again‘ 52 else: 53 chosen = True 54 55 if choice == ‘q‘: done = True 56 if choice == ‘n‘: newuser() 57 if choice == ‘e‘: olduser() 58 59 if __name__ == ‘__main__‘: 60 showmenu()
(b)
以上是关于第7章的主要内容,如果未能解决你的问题,请参考以下文章