Python核心编程第七章笔记及习题记录

来源:互联网 发布:web3.0与云计算 编辑:程序博客网 时间:2024/05/21 14:02

<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">1.字典的比较算法:</span>

(1)首先比较字典的长度

(2)若字典长度相等,比较字典的键,当对应位置的两个键不匹配时,对这两个键直接比较,并返回结果。

(2)若键完全匹配,再比较每个相同的键对应的值,当对应位置的值不匹配时,对这两个值直接比较,并返回结果。

(3)若值也匹配,则为完全匹配,返回0值。

2.dict函数:

 (1)dict函数被用来创建字典,若不提供参数,则为空字典。

(2)若参数为容器类型对象,且可以迭代(例如序列),则每个可迭代的对象必须成对出现。每个值对中,第一个元素是键,第二个元素为值。

      >>>  dict([['x',1],['x',2]])

          {'y':1,'x':2}

  (3)若参数为一个映射对象,例如字典对象,调用dict会从存在的字典里赋值内容生成新的字典。效果与内建方法copy()

相同。

>>>dict8=dict(x=1,y=2)

>>>dict9=dict8.copy()

>>>dict9

{'y':2,'x':1}


3.hash函数

将一个对象传递给hash,返回此对象哈希值。内建函数hash用来判断对象是否可以做字典的键。

将非哈希类型参数传递给hash(),会产生TypeError错误。(不可变类型都是可哈希的)


4.keys()

返回一个列表,包含字典中所有键。

可与for循环一起使用获取字典中的值。

5.values()

返回一个列表,包含字典中所有值。

6.items()

返回一个包含所有(键,值)元组的列表。

7.update()

将一个字典的内容添加到另一字典内,若有重复的键,则该键原有值被新值替换。

8.setdefault()

 检查字典中是否含有某键,若有,返回其值,若无,可以给该键赋默认值。

9.字典的键

(1)不允许一个键对应多个值,当一键多值时,取最后的值。

(2)对于数字,值相等的数字表示同一个键,例如1和1.0

(3)当元组中只包括像数字和字符串的不可变参数,才可以作为字典的键。


习题

7.3

a。穿件一个字典,并把该字典的键按照字母顺序显示出来
b.根据已按照字母顺序排好序的键,显示键和值。

c.按照字母顺序排雷字典的值,并按此顺序显示字典的键和值

<span style="font-size:18px;">#7.3adict1={'z':1,'a':2,'f':3,'d':4,'s':5,'y':6,'j':7}List=dict1.keys()List.sortprint List#7.3bList1=dict1.items()List1.sort()print List1#7.3cList3=[]List2=dict1.values()List2.sort()for i in List2:    for j in dict1:        if dict1[j]==i:            temp=(j,i)            List3.append(temp)print List3</span>

运行结果:

<span style="font-size:18px;">['a', 'd', 'f', 'j', 's', 'y', 'z'][('a', 2), ('d', 4), ('f', 3), ('j', 7), ('s', 5), ('y', 6), ('z', 1)][('z', 1), ('a', 2), ('f', 3), ('d', 4), ('s', 5), ('y', 6), ('j', 7)]</span>

7.4 给定两个长度相同的列表,用这两个列表里的所有数据组成一个字典。

<span style="font-size:18px;">List1=[1,2,3,4,5,6,7,8]List2=['abc','def','ghi','jkl','mno','pqr','stu','vwy']dict1={}Len=len(List1)for i in range(Len):    dict1[List1[i]]=List2[i]print dict1</span>
运行结果:

<span style="font-size:18px;">{1: 'abc', 2: 'def', 3: 'ghi', 4: 'jkl', 5: 'mno', 6: 'pqr', 7: 'stu', 8: 'vwy'}</span>
7.5暂时只写了a,b两小问

<span style="font-size:18px;">import timeimport datetimedb={}Time={}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    print 'Welcome!'    LTime=datetime.datetime.now()    Time[name]=LTime    print LTimedef olduser():    name=raw_input('login: ')    pwd=raw_input('passwd: ')    checkID=db.setdefault(name,0)    if checkID==0:        print 'ID you entered is wrong'    else:        passwd=db.get(name)        if passwd==pwd:            print 'welcome back',name            NTime=datetime.datetime.now()            print NTime              Time[name]=NTime        else:            print 'login incorrect''''删除用户'''def delet():    name=raw_input('enter the name you want delete:')    checkID=db.setdefault(name,0)    if checkID==0:        print 'the name you want delete not exit.'    else:        del db[name]        print 'the name is deleted'#显示所有用户def show():    List=db.items()    print List#管理菜单    def Manag():    prompt='''   删除用户请输入d   显示系统用户请输入s   :    '''    choice=raw_input(prompt).lower()    if choice =='d':delet()    elif choice=='s':show()    else:print 'you enter is wrong'def showmenu():    prompt='''    (N)ew User Login    (E)xisting User Login    (Q)uit    (M)anageenter choice:'''    done=False    while not done:        chosen=False        while not chosen:            try:                choice=raw_input(prompt).strip()[0].lower()            except (EOFError,KeyboardInterrupt):                choice='q'            print '\nYou picked:[%s]',choice            if choice not in 'neqm':                print 'incalid option,try again'            else:                chosen=True        if choice =='q':done=True        if choice =='n':newuser()        if choice =='e':olduser()        if choice =='m':Manag()showmenu()</span>

7.7 颠倒字典中的键和值,用前者的键作值,前者的值作键。

dict1={1:'a',2:'b',3:'c',4:'d',5:'e',6:'f',7:'g'}dict2={}List1=dict1.values()List2=dict1.keys()Len=len(List1)for item in range(Len):    dict2[List1[item]]=List2[item]print dict2

7.8 穿件一个简单的雇员姓名和编号的程序........(附加题就不写了,和前面那题类似)

dict1={}print 'enter a name equal to -1 to end.'while True:    name=raw_input('please enter a name:')    if name=='-1':        break    number=raw_input('and enter his number:')        dict1[name]=numberList1=dict1.items()List1.sort()print List1    

7.9翻译。
(7.9c的代码在注释里)
#7.9adict1={}def tr(srcstr,dsstr,string):       string.lower()'''不区分大小写'''    for i in range(len(srcstr)):        dict1[srcstr[i]]=dsstr[i]        '''7.9c        new_srcstr=srcstr[:len(dsstr)]        '''    for j in range(len(string)):        if string[j] in srcstr:            '''7.9c            if string[j] in new_srcstr:                string=string[:j]+dict1[string[j]]+string[j+1:]            else:                string=string[:j]+string[j+1:]            '''            string=string[:j]+dict1[string[j]]+string[j+1:]    return stringsrcstr='abcdefghijkl'dsstr= 'mnopqrstuvwx'string=raw_input('please enter a string:')print 'transalte string is',tr(srcstr,dsstr,string)


7.10 编写‘rot13’翻译器。

def rot13(string):    for i in range(len(string)):        num=ord(string[i])        if num>64 and num<78 or num>96 and num<110:            string=string[:i]+chr(num+13)+string[i+1:]        elif num>77 and num<91 or num>109 and num<123:            string=string[:i]+chr(num-13)+string[i+1:]    return stringstring=raw_input('Enter string to rot13:')print'Your string to en/decrypt was:[%s]'%stringprint 'The rot13 string is:',rot13(string)
运行结果:

Enter string to rot13:This is a short sentenceYour string to en/decrypt was:[This is a short sentence]The rot13 string is: Guvf vf n fubeg fragrapr>>> ================================ RESTART ================================>>> Enter string to rot13:Guvf vf n fubeg fragraprYour string to en/decrypt was:[Guvf vf n fubeg fragrapr]The rot13 string is: This is a short sentence

7.13

import randomA=set()B=set()for i in range(10):    item=random.randint(0,9)    A.add(item)print Afor j in range(10):    item=random.randint(0,9)    B.add(item)print Bprint A|Bprint A&B
运行结果:

set([2, 4, 5, 6, 7, 8, 9])set([0, 3, 6, 7, 8, 9])set([0, 2, 3, 4, 5, 6, 7, 8, 9])set([8, 9, 6, 7])
7.14用户验证

import randomA=set()B=set()for i in range(10):    item=random.randint(0,9)    A.add(item)print Afor j in range(10):    item=random.randint(0,9)    B.add(item)print Bfor k in range(3):    Input1=raw_input('Now,input your think of A|B:')    Input2=raw_input('and A&B:')    C=set()    D=set()    for i in Input1:        C.add(int(i))    for j in Input2:        D.add(int(j))    if (A|B)==(C|D) and (A&B)==(C&D):        print 'Congratulations,you are right!'        break    else:        print'You are wrong!'        k+=1if k>2:    print'The right answer of A|B is:',A|B    print'The right answer oF A&B is:',A&B










0 0