字典的周遊 | Python從入門到精通:進階篇之十六
集合(set)
集合和清單非常相似,都是在對象中存儲資料。但也有不同點。
- 集合中隻能存儲不可變對象
- 集合中存儲的對象是無序(不是按照元素的插入順序儲存)
- 集合中不能出現重複的元素
關于操作方法,在
官網文檔中查找。

建立集合 {}
# 使用 {} 來建立集合
s = {10,3,5,1,2,1,2,3,1,1,1,1} # <class 'set'>
#s = {[1,2,3],[4,6,7]} TypeError: unhashable type: 'list'
print(s,type(s))
執行結果:
集合當中隻能存儲不可變對象。
建立集合 set()
# 使用 set() 函數來建立集合
s = set() # 空集合
# 可以通過set()來将序列和字典轉換為集合
s = set([1,2,3,4,5,1,1,2,3,4,5])
s = set('hello')
s = set({'a':1,'b':2,'c':3}) # 使用set()将字典轉換為集合時,隻會包含字典中的鍵
print(s,type(s))
建立集合
# 建立集合
s = {'a' , 'b' , 1 , 2 , 3}
print(s,type(s))
#print(s[0]) 集合不可以通過索引去操作
print(list(s)[0]) #如果需要通過索引去操作,則需要先将集合轉換成清單
檢查集合中的元素 in/not in
# 使用in和not in來檢查集合中的元素
# print('a' in s)
print('c' in s)
擷取集合中元素的數量 len()
# 使用len()來擷取集合中元素的數量
print(len(s))
添加元素 add()
# add() 向集合中添加元素
s.add(10)
s.add(30)
print(s,type(s))
添加元素 update()
# update() 将一個集合中的元素添加到目前集合中
# update()可以傳遞序列或字典作為參數,字典隻會使用鍵
s2 = set('hello')
s.update(s2)
s.update((10,20,30,40,50))
s.update({10:'ab',20:'bc',100:'cd',1000:'ef'})
print(s,type(s))
删除 pop()
# pop()随機删除并傳回一個集合中的元素
#s.pop()
result = s.pop()
print(reult)
print(s,type(s))
删除元素 remove()
# remove()删除集合中的指定元素
s.remove(100)
s.remove(1000)
print(s,type(s))
清空集合 clear()
# clear()清空集合
s.clear()
淺複制 copy()
# copy()對集合進行淺複制
s2 = s.copy()
以上是集合的基本介紹。
配套視訊課程,點選這裡檢視
擷取更多資源請訂閱
Python學習站