集合能夠理解成一個總體,學習Python的學生能夠是一個集合體;學習Linux的學生能夠是一個集合體
python
pythoners = ['jason', 'nick', 'tank', 'sean'] linuxers = ['nick', 'egon', 'kevin'] # 即報名pythoners又報名linux的學生 py_li_list = [] for stu in pythoners: if stu in linuxers: py_li_list.append(stu) print(f"pythoners and linuxers: {py_li_list}") # pythoners and linuxers: ['nick']
集合用於關係運算的結合體,因爲集合內的元素無序且集合元素不可重複,所以集合能夠去重,可是去重後的集合會打亂原來元素的順序。
linux
在{}內用逗號分隔開多個元素,每一個元素必須是不可變類型
app
age = {18,12,9,21,22} name = {'nick','egon','rocky'}
**優先掌握**
學習
1.長度len
code
2.成員運算in/not in
rem
3.|並集、union
io
4.&交集、intersection
class
5.-差集、difference
date
6.補集、symmetric_difference
數據類型
hobby_set = {'run','read','paly'} print(len(hobby_set)) # 3
hobby_set = {'run','read','paly'} print('swim' in hobby_set) # False print('run' in hobby_set) # True
hobby_set = {'run','read','paly'} hobby_set2 = {'run','sing','swim'} print(hobby_set | hobby_set2) # {'paly', 'swim', 'read', 'run', 'sing'} print(hobby_set.union(hobby_set2)) # {'read', 'sing', 'run', 'swim', 'paly'}
hobby_set = {'run','read','paly'} hobby_set2 = {'run','sing','swim'} print(hobby_set & hobby_set2) # {'run'} print(hobby_set.intersection(hobby_set2)) # {'run'}
hobby_set = {'run','read','paly'} hobby_set2 = {'run','sing','swim'} print(hobby_set - hobby_set2) # {'read', 'paly'} print(hobby_set.difference(hobby_set2)) # {'read', 'paly'}
hobby_set = {'run','read','paly'} hobby_set2 = {'run','sing','swim'} print(hobby_set ^ hobby_set2) # {'swim', 'sing', 'paly', 'read'} print(hobby_set.ymmetric_difference(hobby_set2)) # {'swim', 'sing', 'paly', 'read'}
**瞭解**
1.pop隨機刪除
2.clear清空
3.update更新
4.copy複製
5.移除remove/discard
remove和discard的區別:
remove在移除集合裏沒有的元素的時候,程序會報錯,而discard不會報錯