python Day8 :集合

来源:互联网 发布:淘宝店铺二维码在哪里 编辑:程序博客网 时间:2024/05/16 15:23

(1)基础

set和frozenset分别创建可变与不可变集合,集合中的元素不重复。
aset=set('david')Out[2]: {'a', 'd', 'i', 'v'}type(aset)
Out[3]: set
dset=set([12,33,44,55])
dsetOut[29]: {12, 33, 44, 55}//(创建数值集合)

(2)一些集合常见运算:

bset=frozenset('david')
'c' in asetOut[4]: False'd' not in asetOut[5]: Falseaset==bsetOut[7]: Trueset('dav')<=asetOut[8]: Trueaset>=set('dave')Out[9]: False
 cset=set('dave')
aset&csetOut[12]: {'a', 'd', 'v'}
aset|csetOut[14]: {'a', 'd', 'e', 'i', 'v'}
aset-csetOut[15]: {'i'}
aset^csetOut[16]: {'e', 'i'}

(3)一些指令函数

面向所有集合的一些函数
issubset(),issuperset(),union(),intersection(),difference(),symmetric_difference(),copy()
aset.issubset(cset)#测试是否 s 中的每一个元素都在 tOut[19]: Falseaset.union(cset)Out[20]: {'a', 'd', 'e', 'i', 'v'}aset.intersection(cset)Out[21]: {'a', 'd', 'v'}aset.difference(cset)Out[22]: {'i'}dset=aset.copy()dsetOut[24]: {'a', 'd', 'i', 'v'}aset.symmetric_difference(cset)Out[25]: {'e', 'i'}

总体上和逻辑运算没太大差别。

面向可变集合的运算:
add(),remove(),discard(),pop(),clear(),update()等
discard()是如果在 set 中存在元素 x, 则删除 。remove()是从 set “s”中删除元素 x, 如果不存在则引发 KeyError  
pop()是删除并且返回 set “s”中的一个不确定的元素, 如果为空则引发 KeyError  

(4)一次小程序练习:

用字典创建一个平台的用户信息(包含用户名和密码)管理系统,新用户可以用与现有系统帐号不冲突的用户名创建帐号,已存在的老用户则可以用用户名和密码登陆重返系统。
adict= {'a':1234,'b':1235,'c':12}def newusers(adict):    print('please input the new name')    new_name=input("")    if new_name in adict.keys():        print('The name has exsited.Please try again')        newusers(adict)    else:        adict[new_name]=input("")#新用户的加入,文件的更新需要关闭字典然后实现def oldusers(adict):    print('please input your name')    user_name=input("user_name: ")    user_code=eval(input("user_code: "))    if  str(adict[user_name])==user_code:          print(user_name, 'welcome back ')      else:          print('login incorrect') #旧用户的判断,在这里input的输入123也是str形式,而字典中的1234为int形式,是因为input在py3.0以后默认输入为str,需要加上evaldef showmenu():     option = """ (N)ew User Login (E)xisting User Login (Q)uit Enter choice: """#option的赋值,我一步步加断点,想看看是不是输入的值“qne”被加到了option的末尾,可能是吧,不是很清楚     done = False     while not done:         chosen = False         while not chosen:             try:                 choice = input(option).strip()[0].lower()#取输入的最后一位             except(EOFError, KeyboardInterrupt):#排除报错                 choice = 'q'             print('\nYou picked: [%s] \n' % choice)             if choice not in 'neq':                 print('invalid option, try again!')             else:                 chosen = True         if choice == 'q':done = True         if choice == 'n':newusers(adict)         if choice == 'e':oldusers(adict)if __name__ == '__main__':     showmenu()
#程序很简单,抄抄补补,有那么长时间没有尝试了,我就想看看choice的值是怎么变化的,但是还是失败了,很遗憾啊,


原创粉丝点击