08-集合

集合

特點(diǎn):
1.不同元素組成
2.無序
3.集合中的元素必須是不可變類型

? 集合中只能包含數(shù)字、字符串、元組等不可變類型(或者說可哈希)的數(shù)據(jù),而不能包含列表、字典、集合等可變類型的數(shù)據(jù)。


1. 集合的創(chuàng)建

1.1 使用 {} 創(chuàng)建

語(yǔ)法格式:set_name = {element1,element2,...,elementn}

a = {1, 'c', 1, (1, 2, 3), 'c'}
print(a)  # out: {1, 'c', (1, 2, 3)}


1.2 set()函數(shù)創(chuàng)建集合

作用:將字符串、列表、元組、range() 對(duì)象等可迭代對(duì)象轉(zhuǎn)換成集合

語(yǔ)法格式:set_name = set(iteration)

set1 = set("acbjkb")
set2 = set([1, 2, 3, 4, 5])
set3 = set((1, 2, 3, 4, 5))
print("set1:", set1)  # out: set1: {'c', 'b', 'a', 'k', 'j'}(隨機(jī)的)
print("set2:", set2)  # out: set3: {1, 2, 3, 4, 5}
print("set3:", set3)  # out: set3: {1, 2, 3, 4, 5}


2. 訪問集合元素及向集合中添加元素

2. 1 訪問集合元素最常用的方法:使用循環(huán)結(jié)構(gòu)

作用:將集合中的數(shù)據(jù)逐一讀取出來。

a = {1, 'c', 1, (1,2,3), 'c'}
for ele in a:
    print(ele,end=' ')  # out: 1 c (1, 2, 3)


2. 2 添加元素

只能是數(shù)字、字符串、元組或者布爾類型(True 和 False)值,不能添加列表、字典、集合這類可變的數(shù)據(jù),否則 Python 解釋器會(huì)報(bào) TypeError 錯(cuò)誤。

語(yǔ)法格式:set_name.add(element)

a = {1, 2, 3}
a.add((1, 2))
print(a)  # out: {(1, 2), 1, 2, 3}
a.add([1, 2])
print(a)  # out: 報(bào)錯(cuò)


3. 刪除集合及集合中的元素

3. 1 刪除集合

語(yǔ)法格式:del(set_name)

a = {1,'c',1,(1,2,3),'c'}
del(a)


3. 2 刪除集合中指定元素

語(yǔ)法格式:set_name.remove(element) , set_name.discard(element)

a = {1, 2, 3}
a.remove(1)
print(a)  # out: {2, 3}
a.remove(1)
print(a)  # out: 報(bào)錯(cuò),1已經(jīng)被刪除,因此不能再使用remove()方法刪除

b = {4, 2, 3}
b.remove(1)
print(b)  # out: {2, 3}
b.discard(1)
print(b)  # out: {2, 3}
b.discard(1)
print(b)  # out: {2, 3}

remove()discard()的區(qū)別:當(dāng)刪除集合中元素失敗時(shí),remove()方法會(huì)拋出錯(cuò)誤,而discard()方法不會(huì)拋出任何錯(cuò)誤。

3.3 pop()和clear()方法

語(yǔ)法格式:set_name.pop() , set_name.clear()

s = {1, 2, 3, 4, 5, 6}
s.pop()  # out: pop刪除時(shí)是無序的隨機(jī)刪除
print(s)  # out: {2, 3, 4, 5, 6}

s = {1, 2, 3, 4, 5, 6}
s.clear()  # 清空集合
print(s)  # out: set()


4.集合的運(yùn)算

集合的運(yùn)算:
交( & ):取兩集合公共的元素
并( | ):取兩集合全部的元素
差( - ):取一個(gè)集合中另一集合沒有的元素
對(duì)稱差( ^ ):取集合 A 和 B 中不屬于 A&B 的元素

set1 = {1, 3, 5, 7}
set2 = {3, 6, 9, 12}
set1 & set2  # out: {3}
set1 | set2  # out: {1, 3, 5, 6, 7, 9, 12}
set1 - set2  # out: {1, 5, 7}
set2 - set1  # out: {9, 12, 6}
set1 ^ set2  # out: {1, 5, 6, 7, 9, 12}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容