set類型就是集合,集合本身時(shí)不可hash,即可變。
?特點(diǎn):元素之間具有不重復(fù)性,無(wú)序性,用"{}"括住可hash(不可變)的元素(int/str/tuple/bool)
?算術(shù)運(yùn)算:并,交,補(bǔ)集
?兩種類型:set普通集合,frozenset不可變集合
?集合沒(méi)有索引,也是不可以定位一個(gè)元素,所以修改的方法只能先清空后添加。
內(nèi)置函數(shù)
??查詢 -集合是一個(gè)可迭代對(duì)象,可以進(jìn)行for循環(huán)迭代
x = set(('apple', 'banana', 'cherry'))
print(x)
for n in x:
print(n)
--------------------------------------------------
{'cherry', 'apple', 'banana'}
cherry
apple
banana
??增加 add()/update()
fruits = {'apple', 'banana', 'cherry'}
fruits.add('orange')
print(fruits)
--------------------------------------------------------
x = {'apple', 'banana', 'cherry'}
y = {'google', 'microsoft', 'apple'}
x.update(y)
print(x)
??修改 -沒(méi)有直接修改,只能先刪除,后添加。
s = {"劉嘉玲", '關(guān)之琳', "王祖賢","張曼?", "李若彤"}
# 把劉嘉玲改成趙本?
s.remove("劉嘉玲")
s.add("趙本?")
print(s)
??刪除 -pop()/remove()/clear()
fruits = {'apple', 'banana', 'cherry'}
fruits.pop()
print(fruits)
---------------------------------------------------
fruits = {'apple', 'banana', 'cherry'}
fruits.remove('banana')
print(fruits)
---------------------------------------------------
fruits = {'apple', 'banana', 'cherry'}
fruits.clear()
print(fruits)
其他操作函數(shù) (&,|,-,^)都可以取代以下關(guān)鍵字來(lái)運(yùn)算。
# 交集元素
x = {'apple', 'banana', 'cherry'}
y = {'google', 'microsoft', 'apple'}
z = x.intersection(y)
print(z)
x = {'a', 'b', 'c'}
y = {'c', 'd', 'e'}
z = {'f', 'g', 'c'}
result = x.intersection(y, z)
print(result)
---------------------------------------------------------------
# 并集元素
x = {'apple', 'banana', 'cherry'}
y = {'google', 'microsoft', 'apple'}
z = x.union(y)
print(z)
x = {'a', 'b', 'c'}
y = {'f', 'd', 'a'}
z = {'c', 'd', 'e'}
result = x.union(y, z)
print(result)
----------------------------------------------------------------
# 差集元素
x = {'apple', 'banana', 'cherry'}
y = {'google', 'microsoft', 'apple'}
z = x.difference(y)
print(z)
x = {'apple', 'banana', 'cherry'}
y = {'google', 'microsoft', 'apple'}
z = y.difference(x)
print(z)
----------------------------------------------------------------
# 反差集
x = {'apple', 'banana', 'cherry'}
y = {'google', 'microsoft', 'apple'}
z = x.symmetric_difference(y)
print(z)
-----------------------------------------------------------------
# 子集
x = {'a', 'b', 'c'}
y = {'f', 'e', 'd', 'c', 'b'}
z = x.issubset(y)
print(z)
x = {'a', 'b', 'c'}
y = {'f', 'e', 'd', 'c', 'b', 'a'}
z = x.issubset(y)
print(z)
------------------------------------------------------------------
# 超集
x = {'f', 'e', 'd', 'c', 'b', 'a'}
y = {'a', 'b', 'c'}
z = x.issuperset(y)
print(z)
x = {'f', 'e', 'd', 'c', 'b'}
y = {'a', 'b', 'c'}
z = x.issuperset(y)
print(z)
基本的數(shù)據(jù)類型已經(jīng)講完80%了,接下來(lái)會(huì)進(jìn)行一些必要補(bǔ)充。