python核心编程第七章

7.1映射类型:字典

    映射类型不要求用数字值做索引以从一个容器中获取对应的数据项。可以直接“映射“到值,这就是映射类型的原因,映射类型通常被叫做哈希表没事因为字典对象就是哈希类型的。

7.2映射类型操作符

 标准:= <  and

字典的键查找操作符 []

键成员操作 in not in

7.3 映射类型的内建函数和工厂函数

    7.3.1 type() str()  cmp()

cmp()先比元素个素,再比元素中的键,再比值

 

7.4 映射类型内建方法

7.5 字典的键

7.6集合类型

创建:s= set('cheeseshop')

           t= frozenset('bookshop')

更新:s.add('z')

 s.update('pypi')

s.remove('z')

s-=set('pypi')

删除:del

 

7.7 集合类型操作符

1.标准类型操作符

in ,not

== !=

< >=

2.集合类型操作符

1.联合(|)

s|t

2.交集(&)

s & t

3.查补/相对补集(-)

s - t

4.对称差分(^):集合的异或

3.仅适合可变集合的操作符

1.update 和(|=)等价 从已存在集合中添加成员

2. intersection_update和(&=)等价

保留和其他集合的共有成员

3.difference update(-=)

差更新操作

4.symmetric_difference_update()等价

对称差分更新操作(s^),对称差分更新操作会返回一个集合,该集合中的成员仅是原集合s或者另一个集合t的成员

 

7.8 内建函数

7.9 集合内建方法

内建方法和操作符几乎等价,但其中有一个重要的区别:当用操作符时,操作符两边的操作数必须是集合,在使用内建方法时,对象也可以是迭代类型的

 

7.12 练习

1.字典方法。哪个字典方法可以用来把两个字典合并到一起。

dict1.update(dict2)

2.字典的键必须是可哈希的,字典的键的值是来存储数据的位置的如果键是可变对象,它的值发生改变,如果键发生变化,哈希函数会映射到不同的地址来存储数据,哈希函数就不可能可靠的存储或获取相关的数据

内建函数hash()可以判断对象是否可以作为字典的键

3.7–3. 字典和列表的方法。 
(a) 创建一个字典,并把这个字典中的键按照字母顺序显示出来。 
(b) 现在根据已按照字母顺序排序好的键,显示出这个字典中的键和值。 
(c)同(b),但这次是根据已按照字母顺序排序好的字典的值,显示出这个字典中的键和值。 

dict = {'name':'df','old':'18','sex':'boy'}
print sorted(dict.keys())

for i in sorted(dict.keys()):
	print dict[i]

print sorted(dict.values())

for j in sorted(dict.values()):
	for i in dict.keys():
		if j ==dict[i]:
			print i,j

 

4.建立字典。给定两个长度相同的列表,比如说,列表[1, 2, 3,...]和['abc', 'def','ghi',...],用这两个列表里的所有数据组成一个字典,像这样:{1:'abc', 2: 'def', 3: 'ghi',...}

错误的:

list1 = [1,2,3,4,5]
list2 = [a,b,c,d,e]
dict ={}
for i in list1:
	dict.keys() = list[i]
for i in list2:
	dict.values() = list[i]

print dict

改:

 

list1 = [1,2,3,4,5]
list2 = ['a','b','c','d','e']
dict ={}
for i in range(len(list1)):
	dict[list1[i]] = list2[i]

print dict

 

# -*-coding:utf-8 -*-
list1 = [1,2,3,4,5]
list2 = ['a','b','c','d','e']
dict1 = dict(zip(list1,list2))
print dict1

dict2 = dict(zip([1,2,3],['a','sd','sddf']))
print dict2

5.

原文

# -*-coding:utf-8 -*-
db ={}

def newuser():
	prompt = 'login desired:'
	while True:
		name = raw_input(prompt)
		if db.has_key(name):
			prompt = 'name taken, try another:'
			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)u
Enter choice:"""
	
	done = False
	while not done:
	
		chosen = False
		while not chosen:
			try:
			#strip 用来删除字符串中的空白符
				choice = raw_input(prompt).strip()[0].lower()
			except (EOFError, KeyboardInterrupt):
				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()
	

 

a.b.c.e.f.g

# -*-coding:utf-8 -*-
from datetime import datetime
#专门提供哈希算法的库
import hashlib
db ={}

def newuser():
	value =[]
	prompt = 'login desired:'
	while True:
		name = raw_input(prompt)
		#加强对用户名的限制,不允许符号和空白符
		#isalnum判断字符变量是否为字母或者数字,若是则返回1,否则返回0
		if not name.isalnum and ' ' in name:
			print "name format error"
			continue
		else:
			if db.has_key(name):
				prompt = 'name taken, try another:'
				continue
			else:
				break
	
	pwd = raw_input('passwd:')
	#摘要算法,计算出一个字符串的MD5值
	m = hashlib.md5()
	m.update(pwd)
	#储存密码和日期
	value.append(m.hexdigest())
	value.append(datetime.now())
	db[name]= value
	print "new user name is %s ,register time is %s " %(name,db[name][1])
def olduser():
	name = raw_input('login:')
	pwd = raw_input('passwd:')
	m = hashlib.md5()
	m.update(pwd)
	passwd = db.get(name)
	if passwd[0] == m.hexdigest():
		newtime = datetime.now()
		if (newtime-db[name][1]).days==0 and (newtime-db[name][1]).seconds<14400:
			print 'you have logined in at %s' %(db[name][1])
		else:
			passwd[1] = newtime
			print "welcome back%s,login time is %s" %(name,passwd[1])
	else:
		print 'login incorrect'
#显示系统中所有用户的名字和他们的密码清单,可以选择删除其中一个用户
def removeuser():
	print db
	name = raw_input('input a name to remove')
	if name in db:
		db.pop(name)
	else:
		print "input error"

def userlogin():
	while True:
		name = raw_input('login name desired: ').lower()
		if not name.isalnum() and '' in name:  
			print'name format error'  
			continue  
		else:  
			if not db.has_key(name):  
				print 'user name is not in db'  
				answer=raw_input('register a new user? y/n').lower()  
				if 'y'==answer:  
					newuser()  
					break  
				elif 'n'==answer:  
					break  
			else:  
				print 'user name is already in db'  
				olduser()  
				break  
  
		
		
def showmenu():
	prompt = """
(U)ser Login
(R)emove a existing user
(Q)uit
Enter choice:"""
	
	done = False
	while not done:
	
		chosen = False
		while not chosen:
			try:
			#strip 用来删除字符串中的空白符
				choice = raw_input(prompt).strip()[0].lower()
			except (EOFError, KeyboardInterrupt):
				choice = 'q'
			print '\nYou picked: [%s]' %choice
			if choice not in 'urq':
				print 'invalid option, try again'
			else:
				chosen = True
		if  choice == 'q':done = True
		if choice == 'r':removeuser()
		if choice == 'u':userlogin()
		
		
if __name__ == '__main__':
	showmenu()

 

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

# -*-coding:utf-8 -*-
dict1 = {'name':'df','age':'18'}
dict2 = {}
for key,value in dict1.items():
	dict2[value] = key
print dict2

 

 

8. 人力资源。创建一个简单的雇员姓名和编号的程序。让用户输入一组雇员姓名和编号。你的程序可以提供按照姓名排序输出的功能,雇员姓名显示在前面,后面是对应的雇员编号。附加题:添加一项功能,按照雇员编号的顺序输出数据。

# -*-coding:utf-8 -*-
dict = {}
print "按q时停止输入姓名"
while True:
	name = raw_input("输入雇员姓名:")
	if name == 'q':
		break
	dict[name] = raw_input("输入雇员编号:")

dictkeys = dict.keys()
dictkeys.sort()
for i in dictkeys:	
	print "姓名:%s,编号:%s" %(i,dict[i])

for i in sorted(dict.values()):
	for j in dict.keys():
		if dict[j] == i:
			print "编号:%s,姓名:%s" %(i,j)
	

7-11定义。什么组成字典中合法的键? 举例说明字典中合法的键和非法的键。

可哈希的可以作为字典中合法的键,如数字,字符串 ,非法的如字典,列表

 

7-12

定义。  
(a)在数学上,什么是集合?  
(b)在 Python 中,关于集合类型的定义是什么?

a.在数学上,把不同元素组成的集合,集合的成员通常被称作集合元素

b.在Python,集合是一组无序排列的可哈希的值

 

7-13

7–13. 随机数。修改练习5-17 的代码:使用random 模块中的randint()或randrange()方法生成一个随机数集合:从0 到9(包括9)中随机选择,生成1 到10 个随机数。这些数字组成集合A(A 可以是可变集合,也可以不是)。同理,按此方法生成集合B。每次新生成集合A 和B 后,显示结果 A | B 和 A & B
 

# -*-coding:utf-8 -*-
import random
list_A= []
list_B=[]


for i in range(0,10):
	list_A.append(random.randint(0,9))
	list_B.append(random.randint(0,9))
A= set(list_A)
B= set(list_B)
print A
print B
print A|B 
print A&B

 

7-14用户验证。修改前面的练习,要求用户输入A|B和A&B的结果,并告诉用户的答案是否正确,而不是将A|B和A&B的结果直接显示出来。如果用户回答错误,允许他修改解决方案,然后重新验证用户输入的答案。如果用户三次提交的答案均不正确,程序将显示正确结果。附加题:运用你关于集合的知识,创建某个集合的潜在子集,并询问用户此潜在子集是否真是该集合的子集,要求和主程序一样有显示更正和答案的功能。

a.

# -*-coding:utf-8 -*-
import random
list_A= []
list_B=[]
answer1=[]
answer2=[]

for i in range(0,10):
	list_A.append(random.randint(0,9))
	list_B.append(random.randint(0,9))
A= set(list_A)
B= set(list_B)
print A
print B
#也可以用遍历完成,for i in range(0,3)
k=0
while k<3:
	ans1 = raw_input("please input the answer of A|B,like[1,2,3]")
	ans2 = raw_input("please input the answer of A&B,like[1,2,3]")
	#执行的时候','和输入的,报错
	for i in ans1.split(','):
	#忘记加int了
		answer1.append(int(i))
	ans3 = set(answer1)
	for j in ans2.split(','):
		answer2.append(int(j))
	ans4 = set(answer2)


	if ans3==A|B and ans4==A&B:
		print "congratulations,you are right"
		break
	else:
		print "sorry ,you can try again"
	k+=1
	if k==3:
		print "The right answer is that:%s,%s" %(A|B, A&B)

    

b,附加

# -*-coding:utf-8 -*-
import random
A=[]
B=[]
#创建子集
for i in range(0,10):
	A.append(random.randint(0,9))
C =set(A)
for i in range(0,random.randint(0,10)):
	B.append(random.randint(0,9))
D =set(B)
print "C is",C
print "D is",D
#询问
k=0
while k<3:
	ans = raw_input("D是C的子集吗?yes or no")
	if ans == 'yes':
		if D.issubset(C):
			print "you are right!"
			break
		else:
			print "you can try again!"
	if ans =='no':
		if not D.issubset(C):
			print "you are right!"
			break
		else:
			print "you can try again!"
	k+=1
	if k==3:
		print"The subset of C is",C.intersection(D)
	

7.15

这个练习取材于http://math.hws.edu/ 在线免费Java 教材中的练习12.2。编写一个程序允许用户选择两个集合:A 和B, 及运算操作符。例如,in, not in, &, |, ^, <,<=, >, >=, ==, !=, 等. (你自己定义集合的输入语法,它们并不一定要像Java 示例中那样用方括号括住。)解析输入的字符串,按照用户选择的运算进行操作。你写的程序代码应该比Java 版本的该程序更简洁。

不是自己写的

#eval函数的作用是把字符串当作表达式来求值,repr()表达式是把表达式和变量当作字符串
tmp1=eval(raw_input('pls input set A,separate by comma:'))  
tmp2=eval(raw_input('pls input set B:separate by comma:'))  
A=set(tmp1)  
B=set(tmp2)  
print A  
print B  
while True:  
    op=raw_input('pls choose a operator from (in,not in,&,|,^,<,<=,>,>=,==,!=) for A operator B:')  
    if 'in'==op:  
        print 'A in B is: ',A in B  
    elif 'not in'==op:  
        print 'A not in B is: ',A not in B  
    elif '&'==op:  
        print 'A & B is: ',A&B  
    elif '|'==op:  
        print 'A | B is: ',A|B  
    elif '^'==op:  
        print 'A ^ B is: ',A^B  
    elif '<'==op:  
        print 'A < B is: ',A<B  
    elif '<='==op:  
        print 'A <= B is: ',A<=B  
    elif '>'==op:  
        print 'A > B is: ',A>B  
    elif '>='==op:  
        print 'A >= B is: ',A>=B  
    elif '=='==op:  
        print 'A == B is: ',A==B  
    elif '!='==op:  
        print 'A != B is: ',A!=B  
    else:  
        print 'input error'  
        break  

 

转载于:https://my.oschina.net/finndai/blog/747752

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值