(1)基礎
set和frozenset分別創建可變與不可變集合,集合中的元素不重複。
aset=set('david')
Out[2]: {'a', 'd', 'i', 'v'}
type(aset)
Out[3]: set
dset=set([12,33,44,55])
dset
Out[29]: {12, 33, 44, 55}//(創建數值集合)
(2)一些集合常見運算:
'c' in aset
Out[4]: False
'd' not in aset
Out[5]: False
aset==bset
Out[7]: True
set('dav')<=aset
Out[8]: True
aset>=set('dave')
Out[9]: False
cset=set('dave')
aset&cset
Out[12]: {'a', 'd', 'v'}
aset|cset
Out[14]: {'a', 'd', 'e', 'i', 'v'}
aset-cset
Out[15]: {'i'}
aset^cset
Out[16]: {'e', 'i'}
(3)一些指令函數
面向所有集合的一些函數
issubset(),issuperset(),union(),intersection(),difference(),symmetric_difference(),copy()
aset.issubset(cset)#測試是否 s 中的每一個元素都在 t
Out[19]: False
aset.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()
dset
Out[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,需要加上eval
def 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的值是怎麼變化的,但是還是失敗了,很遺憾啊,