2019-03-14

1.什么是集合(set)

python內置的容器型數據類型.可變(支持增刪),無序(不支持下標操作)

{元素1,元素2,元素3...}

元素要求是不可變并且唯一

set1 = {1, 2, 3, 'abc', 100, (1, 2), 1, 1}
print(set1, type(set1))

空集合: set()

set3 = set()
print(type(set3))

2.查

集合沒有辦法單獨取出某一個元素;只能遍歷

for item in set1:
print(item)

3.增

集合.add(元素) - 在集合中添加指定的元素

set2 = {100, 2, 5, 20}
set2.add(200)
print(set2)

集合.update(序列) - 將序列中的元素(不可變的)添加到集合中

set2.update('abc')
print(set2)

set2.update({'aa': 11, 'bb': 22, 'a': 100})
print(set2)

4.刪

集合.remove(元素) - 刪除集合中指定元素, 元素不存在會報錯

set2 = {100, 2, 5, 20}
set2.remove(100)
print(set2)

集合.clear() - 清空集合

set2.clear()
print(set2)

5.改(集合不支持改操作)

6.數學集合運算(集合應用的重點)

包含關系(>=, <=)、并集()、交集、差集、補集

1)包含關系

集合1 >= 集合2 - 判斷集合1中是否包含集合2

集合1 <= 集合2 - 判斷集合2中是否包含集合1

print({100, 2, 3, 200, 300, 400, 1} >= {1, 2, 3})

2)并集(|)

集合1 | 集合2 - 將集合1和集合2中的元素合并在一起產生新的集合(會去重)

set1 = {1, 2, 3, 4, 5}
set2 = {1, 2, 3, 8, 9, 10}
print(set1 | set2)

交集(&)

集合1 & 集合2

print(set1 & set2)

差集(-)

集合1 - 集合2 - 集合1中除了和集合2公共的元素以外的元素

print(set1 - set2)

補集(^)

print(set1 ^ set2)

7.相關的操作

in / not in

print(1 in {1, 2, 3})

set()

print(set([19, 23, 19, 0, 0, 0, 0]))

總結:集合的應用主要表現在去重和數據集合運算

練習: 用三個列表表示三門學科的選課學生姓名(一個學生可以同時選多門課),

1. 求選課學生總共有多少人

2. 求只選了第一個學科的人的數量和對應的名字

3. 求只選了一門學科的學生的數量和對應的名字

4. 求只選了兩門學科的學生的數量和對應的名字

5. 求選了三門學生的學生的數量和對應的名字

names1 = ['name1', 'name2', 'name3', 'name4', 'name5', 'name6']
names2 = ['name1', 'name2', 'name7', 'name8', 'name9', 'name10']
names3 = ['name2', 'name3', 'name4', 'name7', 'name11', 'name12']

total0 = set(names1) | set(names2) | set(names3)
print('選課學生總共有多少人:%d' % len(total0))

total = set(names1) - set(names2) - set(names3)
total = set(names1) - (set(names2) | set(names3))
print('只選了第一個學科的人的數量:%d,對應的名字:%s' % (len(total), str(total)[1:-1]))

total1 = (set(names1) ^ set(names2) ^ set(names3)) - (set(names1) & set(names2) & set(names3))
print('只選了一門學科的學生的數量:%d, 對應的名字:%s' % (len(total1), str(total1)[1:-1]))

所有學生 - 只選了一科的學生 - 選了三科的學生

total2 = total0 - total1 - (set(names1) & set(names2) & set(names3))
print('只選了兩門學科的學生的數量:%d, 對應的名字:%s' % (len(total2), str(total2)[1:-1]))

total3 = set(names1) & set(names2) & set(names3)
print('選了三門學科的學生的數量:%d, 對應的名字:%s' % (len(total3), str(total3)[1:-1]))

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容