全文共5092字,預計學習時長10分鐘
本文將介紹Python的內置集合模塊,用於支持集合和鍵值對等數學概念。
一、什麼是集合?
集合是一組用於儲存唯一值的序列。
初始化
可使用花括號{}定義集合。
>>> numSet = {1, 2, 3, 4, 5}
>>> print(numSet)
{1, 2, 3, 4, 5}
若在初始化中鍵入重複值,則只保留一個元素。
>>> numSet = {1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5}
>>> print(numSet)
{1, 2, 3, 4, 5}
也可使用內置的 set函數進行空集初始化。
>>> emptySet = set()
>>> print(emptySet)
set()
注意:集合元素是不可更改的,在集合中加入可變對象會報錯。
>>> tuple1 = (1, 2, 3)
>>> tuple2 = (4, 5, 6)
>>> tupleSet = {tuple1, tuple2} # no error as tuples are immutable
>>> print(tupleSet)
{(4, 5, 6), (1, 2, 3)}
>>> list1 = [1, 2, 3]
>>> list2 = [4, 5, 6]
>>> listSet = {list1, list2} #will raise error as lists are mutable
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
加入元素
使用內置 add函數向集合中加入元素。
>>> numSet = {1, 2, 3, 4, 5}
>>> numSet.add(6)
>>> print(numSet)
{1, 2, 3, 4, 5, 6}
注意:在集合中加入重複元素是無效的,此情況下也不會報錯。
>>> numSet = {1, 2, 3, 4, 5}
>>> numSet.add(5)
>>> print(numSet)
{1, 2, 3, 4, 5}
刪除元素
使用內置remove函數刪除集合中元素。
>>> numSet = {1, 2, 3, 4, 5}
>>> numSet.remove(5)
>>> print(numSet)
{1, 2, 3, 4}
注意:刪除集合中不存在的元素不會報錯。
>>> numSet = {1, 2, 3, 4, 5}
>>> numSet.remove(99)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 99
集合長度
使用內置len函數查找集合長度。
>>> numSet = {1, 2, 3, 4, 5}
>>> len(numSet)
5
查找
使用in運算符查找集合中元素。
>>> numSet = {1, 2, 3, 4, 5}
>>> 2 in numSet
True
>>> 99 in numSet
False
接下來介紹如何執行集合操作。
交集
使用 &運算符尋找兩個集合的交集。
>>> setA = {1, 2, 3, 4, 5}
>>> setB = {3, 4, 5, 6, 7}
>>> intersection = setA & setB
>>> print(intersection)
{3, 4, 5}
併集
使用|運算符將兩個集合合併。
>>> setA = {1, 2, 3, 4, 5}
>>> setB = {3, 4, 5, 6, 7}
>>> union = setA | setB
>>> print(union)
{1, 2, 3, 4, 5, 6, 7}
補集
補集返回值為僅在第一個集合中出現的值。
使用-運算符尋找補集。
>>> setA = {1, 2, 3, 4, 5}
>>> setB = {3, 4, 5, 6, 7}
>>> difference = setA - setB
>>> print(difference)
{1, 2}
>>> reverseDifference = setB - setA
>>> print(reverseDifference)
{6, 7}
集合對稱差
對稱差返回值是由只屬於兩個集合中任一集合,而非全部集合的元素組成的集合。
使用 ^ 運算符尋找兩個集合的對稱差。
>>> setA = {1, 2, 3, 4, 5}
>>> setB = {3, 4, 5, 6, 7}
>>> symmDiff = setA ^ setB
>>> print(symmDiff)
{1, 2, 6, 7}
檢查超集
若集合A含有集合B中所有元素,則集合A為集合B的超集。
使用>=運算符檢驗左側集合是否為右側集合的超集。
>>> bigSet = {1, 2, 3, 4, 5}
>>> smallSet = {3, 4}
>>> isSuperSet = bigSet >= smallSet
>>> print(isSuperSet)
True
使用<= 運算符檢驗右側集合是否為左側集合的超集。
>>> bigSet = {1, 2, 3, 4, 5}
>>> smallSet = {3, 4}
>>> isSuperSet = smallSet <= bigSet
>>> print(isSuperSet)
True
二、如何使用字典?
在Python中,字典用於儲存鍵值對。
初始化
同樣可以使用花括號{}初始化字典,並使用key :value 語法聲明鍵值對。
>>> nameToNumber = {"John" : 1, "Harry" : 2, "Jacob" : 3}
>>> print(nameToNumber)
{'John': 1, 'Harry': 2, 'Jacob': 3}
也可使用內置dict函數初始化空字典。
>>> emptyDict = dict()
>>> print(emptyDict)
{}
還可直接使用空花括號{}初始化空字典。
>>> emptyDict = {}
>>> print(emptyDict)
{}
注意:不可改變字典中的鍵。嘗試使用可變鍵創建字典會報錯。
>>> tupleA = (1, 2, 3) # tuples are immutable
>>> stringA = "I love Python!" # strings are immutable
>>> floatA = 3.14 # float values are immutable
>>> dictA = {tupleA : True, stringA : False, floatA : True} # no error as all keys are immutable
>>> print(dictA)
{(1, 2, 3): True, 'I love Python!': False, 3.14: True}
>>> listB = [1, 2, 3] #list is mutable
>>> dictB = {listB : True} # raises an error as lists are mutable
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
獲取數據
使用方括號([])從字典中獲取鍵值。
>>> nameToNumber = {"John" : 1, "Harry" : 2, "Jacob" : 3}
>>> JohnsNumber = nameToNumber["John"]
>>> print(JohnsNumber)
1
注意:尋找不存在的鍵會報錯。
>>> nameToNumber = {"John" : 1, "Harry" : 2, "Jacob" : 3}
>>> nameToNumber["Sam"]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'Sam'
為避免報錯,可以使用內置 get函數。使用該函數尋找不存在的鍵返回值為None,但不會報錯。
>>> nameToNumber = {"John" : 1, "Harry" : 2, "Jacob" : 3}
>>> johnsNumber = nameToNumber.get("John")
>>> print(johnsNumber)
1
>>> samsNumber = nameToNumber.get("Sam"
>>> print(samsNumber)
None
若字典中缺少鍵,則可以使用get 函數返回默認值。將所需的默認值作為第二個參數傳遞給get 函數。
>>> nameToNumber = {"John" : 1, "Harry" : 2, "Jacob" : 3}
>>> johnsNumber = nameToNumber.get("John", 99)
>>> print(johnsNumber)
1
>>> samsNumber = nameToNumber.get("Sam", 99)
>>> print(samsNumber)
99
修改數據
使用內置setdefault 函數將數據插入字典。
只有在字典中不存在該鍵時,setdefault才會在字典中創建新鍵值對。若該鍵存在,也不會被覆蓋。
>>> nameToNumber = {"John" : 1, "Harry" : 2, "Jacob" : 3}
>>> nameToNumber.setdefault("Sam", 4)
4
>>> print(nameToNumber)
{'John': 1, 'Harry': 2, 'Jacob': 3, 'Sam': 4}
>>> nameToNumber.setdefault("Sam", 99) # no changes as the key already exists
4
>>> print(nameToNumber)
{'John': 1, 'Harry': 2, 'Jacob': 3, 'Sam': 4}
使用內置update函數修改字典中現存值。
>>> nameToNumber = {"John" : 1, "Harry" : 2, "Jacob" : 3}
>>> nameToNumber.update({"Sam" : 4}) # creates new entry
>>> print(nameToNumber)
{'John': 1, 'Harry': 2, 'Jacob': 3, 'Sam': 4}
>>> nameToNumber.update({"Sam" : 99}) # updates existing entry
>>> print(nameToNumber)
{'John': 1, 'Harry': 2, 'Jacob': 3, 'Sam': 99}
也可使用方括號修改現存值。
>>> nameToNumber = {"John" : 1, "Harry" : 2, "Jacob" : 3}
>>> nameToNumber["Sam"] = 4 # creates new entry
>>> print(nameToNumber)
{'John': 1, 'Harry': 2, 'Jacob': 3, 'Sam': 4}
>>> nameToNumber["Sam"] = 99 # updates existing entry
>>> print(nameToNumber)
{'John': 1, 'Harry': 2, 'Jacob': 3, 'Sam': 99}
刪除數據
使用 del命令刪除字典中的鍵。
>>> nameToNumber = {"John" : 1, "Harry" : 2, "Jacob" : 3}
>>> del nameToNumber["John"]
>>> print(nameToNumber)
{'Harry': 2, 'Jacob': 3}
注意:刪除不存在的鍵會報錯。
>>> nameToNumber = {"John" : 1, "Harry" : 2, "Jacob" : 3}
>>> del nameToNumber["Sam"]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'Sam'
迭代
使用內置keys功能在字典中的鍵上進行迭代。
>>> nameToNumber = {"John" : 1, "Harry" : 2, "Jacob" : 3}
>>> names = list(nameToNumber.keys()) # using list() to store in a list
>>> print(names)
['John', 'Harry', 'Jacob']
可以使用內置的values函數迭代字典中的值。
>>> nameToNumber = {"John" : 1, "Harry" : 2, "Jacob" : 3}
>>> values = list(nameToNumber.values())
>>> print(values)
[1, 2, 3]
留言 點讚 關注
我們一起分享AI學習與發展的乾貨
如需轉載,請後臺留言,遵守轉載規範