集合的常用操作及內建方法,資料型別彙總
阿新 • • 發佈:2020-07-14
一、集合的常用操作及內建方法
1、定義 s = {1,2,3,4,5,6,7,8}
注意:集合內的元素必須是不可變型別;
元素與元素之間用逗號隔開,不是鍵值對;
集合內的元素都是無序的
2、空集合
s = set()
ps:定義空集合一定要用set關鍵字
3、作用:
(1)去重,集合內不可能出現相同的元素
(2)關係運算:比如共同好友,共同關注,交叉並集等
ps:用集合就是用上面兩個功能 如果都用不上 那麼就不要用
4、 型別轉換
能夠被for迴圈的資料型別都能夠被轉成集合
s1 = set('egon is o DSB')
print(s1) # {' ', 'e', 's', 'n', 'o', 'i', 'D', 'g', 'B', 'S'}
s2 = set([1,2,3,4,5,6,7,7,7,7,7])
print(s2) # {1, 2, 3, 4, 5, 6, 7}
s3 = set({'username':'jason','password':123})
print(s3) # {'password', 'username'}
5、去重
s = {1,1,1,2,3,3,4,3,2,3,4,6,5,3,}
print(s) # 集合內如果有相同的元素會自動去重
# 去重練習題
l = [4,3,2,3,4,6,7,8,1,2,3]
# 要求1 對列表進行去重不需要保持原來的元素順序
# 先轉成集合
s = set(l)
# 再轉成列表
l1 = list(s)
print(l1)
# 要求2 對列表去重之後需要保持原來的元素順序
new_l = []
for i in l:
if i not in new_l:
new_l.append(i)
print(new_l)
6、關係運算
# 使用者1的好友列表
friends1 = {'jason','tank','tony','jerry'}
# 使用者2的好友列表
friends2 = {'jason','tony','owen','oscar'}
# 1 求兩個使用者的共同好友 交集
# res = friends1 & friends2
# print(res) # {'jason', 'tony'}
# 2 求兩個使用者所有的好友
# res = friends1 | friends2
# print(res) # {'jerry', 'jason', 'oscar', 'tony', 'tank', 'owen'}
# 3 求使用者1獨有的好友
# res1 = friends1 - friends2
# res2 = friends2 - friends1
# print(res1,res2) # {'jerry', 'tank'} {'owen', 'oscar'}
# 4 求兩個使用者各自獨有的好友 對稱差集
# res = friends1 ^ friends2
# print(res) # {'owen', 'jerry', 'tank', 'oscar'}
# 5 子集 父集
s1 = {12,3,4,5,6}
s2 = {12,6}
print(s1 > s2) # s1是否是s2的父集
print(s2 < s1) # s2是否是s1的子集
二、資料型別彙總
1.整型int 2.浮點型float 3.字串str 4.列表list 5.字典dict 6.布林值bool 7.元組tuple 8.集合set