Python 集合操作

#1.創建集合使用{}或者set()函數,創建空的集合,只能使用set()函數,因爲{}是字典
#集合相比於列表和元組,有一個去掉重複元素的特性
set1 = {10, 20, 30, 40, 10}
set2 = set()
print(set1)        #輸出 {40, 10, 20, 30}
#這裏注意,集合的輸出跟定義的順序不一致,也就是說集合沒有順序,所以不支持下標操作
#這裏也去掉了重複的數據
print(set2)        #輸出 set()
print(type(set1))  #輸出 <class 'set'>
print(type(set2))  #輸出 <class 'set'>
set3 = set('abcdefg')
set4 = set('123456')
print(set3)        #輸出 {'g', 'b', 'c', 'e', 'd', 'a', 'f'}
print(set4)        #輸出 {'4', '3', '5', '6', '1', '2'}

=======================================

#2.集合的常見操作
#2.1 增加
#2.1.1 add()函數
#當向集合內增加已經存在的數據時,不進行任何操作
#add()只能向集合裏增加單一數據,如果增加其他的比如一個列表,會報錯
set1 = {"11", "22", "33", "44", "55"}
print(set1)     #輸出 {'11', '55', '33', '44', '22'}
set1.add("11")
print(set1)     #輸出 {'11', '55', '33', '44', '22'}
set1.add(66)
print(set1)     #輸出 {'11', '66', '55', '33', '44', '22'}
#set1.add([11, 33])  #報錯 TypeError: unhashable type: 'list'

#2.1.2 update()函數, 增加的是序列,不能增加單一數據,否則會報錯
set1.update([11, 13, 21, 22, 31, 32, 33])
print(set1)  #輸出 {32, '22', 33, '55', 11, 13, '33', '44', '11', '66', 21, 22, 31}
#set1.update(22) #報錯 TypeError: 'int' object is not iterable
set1 = {"11", "22", "33", "44", "55"}
#2.2刪除
#2.2.1 remove() ,刪除集合中指定數據,如果不存在則報錯
print(set1)         #輸出 {'33', '11', '55', '22', '44'}
#注意,這裏 set1.remove(11),這樣刪除會報錯  KeyError: 11
set1.remove("11")   #輸出 {'33', '55', '22', '44'}
print(set1)
#set1.remove("11")   #報錯 KeyError: '11'

#2.2.2 discard(), 刪除集合中指定數據,如果不存在也不報錯
print(set1)         #輸出 {'44', '55', '33', '22'}
set1.discard('22')
print(set1)         #輸出 {'44', '55', '33'}
set1.discard('22')  #不報錯
print(set1)         #輸出 {'44', '55', '33'}

#2.2.3 pop()函數, 隨機刪除集合中的數據, 並返回這個數據
print(set1)             #輸出 {'33', '44', '55'}
del_data = set1.pop()
print(del_data)         #輸出 33
print(set1)             #輸出 {'44', '55'}
#2.3 查找
#in 和 not in
#2.3.1 in 判斷數據是否在集合,在的話返回True, 不在的話返回 False
set1 = {"11", "22", "33", "44", "55"}
print("11" in set1)  #輸出 True
print(11 in set1)    #輸出 False

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章