python核心编程笔记——Chapter7

Chapter7.映像和集合类型

最近临到期末,真的被各种复习,各种大作业缠住,想想已经荒废了python的学习1个月了。现在失去了昔日对python的触觉和要写简洁优雅代码的感觉,所以临到期末毅然继续python的学习,还特地花了一个小时把之前写的代码和笔记再看了一遍,我想如果再晚一点的话连python是何物都恐怕不知道了!

这一章的习题不知道咋样?但是不管了, let's go !

7.1哪个字典方法可以用来把两个字典合并在一起?

在命令行下输了help({}),看了下dist的内建方法。发现只有update方法比较贴近,看一下update方法:

update(...)
 |      D.update([E, ]**F) -> None.  Update D from dict/iterable E and F.
 |      If E present and has a .keys() method, does:     for k in E: D[k] = E[k]
 |      If E present and lacks .keys() method, does:     for (k, v) in E: D[k] = v
 |      In either case, this is followed by: for k in F: D[k] = F[k]

但是对于两个键完全不同的字典,update方法会将它们合并,但是对于存在部分键相同的字典,update只会起到一个更新作用;

 1 >>> dist1={'a':1,'b':2}
 2 >>> dist2={'c':3,'d':4}
 3 >>> dist3={'a':5,'e':6}
 4 >>> dist2.update(dist1)
 5 >>> dist2
 6 {'a': 1, 'c': 3, 'b': 2, 'd': 4}
 7 >>> dist3.update(dist1)
 8 >>> dist3
 9 {'a': 1, 'b': 2, 'e': 6}
10 >>> dist1.update(dist3)
11 >>> dist1
12 {'a': 1, 'b': 2, 'e': 6}
View Code

但是顺序不同,更新也不同,

1 >>> dist1={'a':1,'b':2}
2 >>> dist2={'c':3,'d':4}
3 >>> dist3={'a':5,'e':6}
4 >>> dist1.update(dist3)
5 >>> dist1
6 {'a': 5, 'b': 2, 'e': 6}
View Code

基本上内建的字典方法就只有这个了吧,可能要功能好一点的话估计得自己写了。

7.3.字典和列表的方法:

(a).创建一个字典,并把字典中的键按照字母顺序显示出来。

(b).按照字母顺序排序好的键,显示出这个字典中的键和值。

(c).按照字母顺序排序好的值,显示出这个字典中的键和值。

应该不难吧。。。。。难就难在通过字典的值来找键没有现成的函数吧。

 1 #!usr/bin/env python
 2 #-*-coding=utf-8-*-
 3 
 4 import string
 5 
 6 ss  =  string.lowercase
 7 dict1 = dict([(ss[i-1],26+1-i) for i in range(1,27)])
 8 print 'dictionary is :'
 9 print dict1
10 dict2 = sorted(dict1.keys())
11 print '(a) :',dict2
12 print '(b) :'
13 for key in dict2:
14     print 'key = %s , value = %d ' % (key,dict1[key])
15 
16 dict3 = sorted(dict1.values())
17 print '(c) :'
18 for value in dict3:
19     for (u,v) in dict1.items():
20         if value == v:
21             print 'key = %s , value = %d' % (u,v)
View Code

7.4.建立字典。用两个相同长度的列表组建一个字典出来。几行能写出来。

 1 #!usr/bin/env python
 2 #-*-coding=utf-8-*-
 3 
 4 def merge(list1,list2):
 5     return dict(zip(list1,list2))
 6 
 7 if __name__ == '__main__':
 8     list1 = [1,2,3]
 9     list2 = ['abc','def','ghi']
10     print merge(list1,list2)

 7.5.按照题目来修改userpw.py,要用到一些外部的模块

(a).用到time模块的函数,显示登录时间。还要要求相差不超过小时,要显示出来。主要还是用到localtime()

(b).添加一个管理菜单,实现以下两种功能:(1).删除一个用户;(2).显示系统中所有用户的名字和他们密码的清单。

应该感觉不难,主要对字典进行操作即可。

(c).对口令进行加密操作,不难,只需要对用户的密码统一加密成sha1(安全哈希算法)码即可。(使用sha模块)

(d).添加图形界面(先挖坑,以后再补)

(e).要求用户名不区分大小写。可以选择先把用户名统一保存为小写形式(或大写形式),验证时也将用户输入的同一转化为小写(或大写)来进行核对。

(f).加强对用户名的限制,不允许符合和空白符。对于字符前后的空白符可以通过使用strip()来消除。其他估计要用到正则来解决。

(g).合并新用户和老用户功能。不难。

  1 #!/usr/bin/env python
  2 #-*-coding=utf-8-*-
  3 
  4 import time #导入time模块
  5 import sha  #导入sha模块
  6 import string #导入string模块
  7 import re  #导入re模块(正则匹配)
  8 
  9 db = {}  #建立字典
 10 
 11 def newuser():
 12     prompt = 'login desired : '
 13     while True:
 14         name = raw_input(prompt)
 15         k = re.search(r'\W+',name)
 16         if k != None:
 17             prompt = 'Your name contains illegal characters,try another: '
 18             continue
 19         if db.has_key(name):
 20             prompt = 'name taken,try another: '
 21             continue
 22         else:
 23              break
 24     pwd = raw_input('password: ')
 25     hash = sha.new()   #新建哈希表
 26     hash.update(pwd)
 27     psd = hash.hexdigest()  #Sha-1码
 28     lt = list(time.localtime()[:-3])   #定义现在的时间戳
 29     info = [psd,lt]   #建立用户的个人信息(没有结构体真蛋疼)
 30     db[string.lower(name)] = info
 31     print "Logining in %d/%d/%d -- %d:%d:%d" % (info[1][0],info[1][1],info[1][2],info[1][3],info[1][4],info[1][5])
 32 
 33 def olduser():
 34     while True:
 35         name = raw_input('login: ')
 36         k = re.search(r'\W+',name)
 37         if k != None:
 38             prompt = 'Your name contains illegal characters,try another: '
 39             continue
 40         else:
 41             break
 42     if db.has_key(string.lower(name)) == False:
 43         c = raw_input('This username does not exist.Do you want to create a user ?')
 44         if string.lower(c) == 'y':
 45             pwd = raw_input('password: ')
 46             hash = sha.new()   #新建哈希表
 47             hash.update(pwd)
 48             psd = hash.hexdigest()  #Sha-1码
 49             lt = list(time.localtime()[:-3])   #定义现在的时间戳
 50             info = [psd,lt]   #建立用户的个人信息(没有结构体真蛋疼)
 51             db[string.lower(name)] = info
 52             print "Logining in %d/%d/%d -- %d:%d:%d" % (info[1][0],info[1][1],info[1][2],info[1][3],info[1][4],info[1][5])
 53     else:
 54         pwd = raw_input('password: ')
 55         hash = sha.new()
 56         hash.update(pwd)
 57         psd = hash.hexdigest()
 58         info = db.get(string.lower(name))
 59         temp = list(time.localtime()[:-3])  #更新时间     
 60         if info[0] == psd:
 61             print 'welcome back',string.lower(name)
 62             print "Logining in %d/%d/%d -- %d:%d:%d" % (temp[0],temp[1],temp[2],temp[3],temp[4],temp[5])
 63             if(abs(info[1][3] - temp[3]) < 4):
 64                 print "You already logged in at:%d/%d/%d -- %d:%d:%d" % (info[1][0],info[1][1],info[1][2],info[1][3],info[1][4],info[1][5])
 65                 info[1] = temp
 66             else:
 67                 print 'login incorrect'
 68 
 69 def manage():
 70 #设定用户权限
 71     while True:
 72         name = raw_input('login(root): ')
 73         k = re.search(r'\W+',name)
 74         if k != None:
 75             prompt = 'Your name contains illegal characters,try another: '
 76             continue
 77         else:
 78             break
 79     pwd = raw_input('password: ')
 80     if pwd != 'root':
 81         print 'login(root) incorrect!'
 82     else:
 83         prompt = """
 84 (D)elete A User
 85 (S)how All Users
 86 
 87 Enter choice:"""
 88         choice = raw_input(prompt).strip()[0].lower()
 89         if choice == 'd':
 90             user = raw_input('Please input user:')
 91             if db.has_key(user):
 92                 db.pop(user)
 93                 print 'Finish!'
 94             else:
 95                 print 'No such user.'
 96         if choice == 's':
 97               print 'All users are as follows:'
 98               for key in db.keys():
 99                 print key
100                 
101 def showmenu():
102     prompt = """
103 (N)ew User Login
104 (E)xisting User Login
105 (Q)uit
106 (M)anage
107 
108 Enter choice:"""
109 
110     done = False
111     while not done:
112         chosen = False
113         while not chosen:
114             try:
115                 choice = raw_input(prompt).strip()[0].lower()
116             except (EOFError,KeyboardInterrupt):
117                 choice = 'q'
118             print '\nYou picked:[%s]' % choice
119             if choice not in 'neqm':
120                  print 'invalid option,try again'
121             else:
122                  chosen = True
123         if choice == 'q':done = True
124         if choice == 'n':newuser()
125         if choice == 'e':olduser()
126         if choice == 'm':manage()
127 
128 if __name__ == '__main__':
129     showmenu()
View Code

 7-7.颠倒字典中的键和值,用一个字典做输入,输出另一个字典,用前者的键做值,用前者的值做键。

将前者字典的键遍历一遍即可。

 1 #!usr/bin/env python
 2 #-*-coding=utf-8-*-
 3 
 4 def change(before):
 5     after = {}
 6     for key in before.keys():
 7         after[before[key]] = key
 8     return after
 9 
10 if __name__ == '__main__':
11     dic = {'x':1,'y':2}
12     print change(dic)

7-9.可以用re模块的sub函数轻松解决,这里就不用字典来多余实现了。

字典这章里面有趣题目都比较少,先凑合吧。

就这样,请多多指教!

posted @ 2014-01-16 21:57  中大黑熊  阅读(620)  评论(0编辑  收藏  举报