深圳網(wǎng)站設(shè)計(jì)公司怎么做十大經(jīng)典廣告營(yíng)銷案例
文章目錄
- 集合
- 1、創(chuàng)建集合
- 2、集合常見操作方法
- 2、1 增加數(shù)據(jù)
- 2、2 刪除數(shù)據(jù)
- 2、3 查找數(shù)據(jù)
- 3、總結(jié)
集合
- 目標(biāo)
- 創(chuàng)建集合
- 集合數(shù)據(jù)的特點(diǎn)
- 集合的常見操作
1、創(chuàng)建集合
創(chuàng)建集合使用{}
或set()
, 但是如果要?jiǎng)?chuàng)建空集合只能使用set()
,因?yàn)?code>{}用來創(chuàng)建空字典。
s1 = {10, 20, 30, 40, 50}
print(s1)s2 = {10, 30, 20, 10, 30, 40, 30, 50}
print(s2)s3 = set('abcdefg')
print(s3)s4 = set()
print(type(s4)) # sets5 = {}
print(type(s5)) # dict
特點(diǎn):
- 集合可以去掉重復(fù)數(shù)據(jù);
- 集合數(shù)據(jù)是無序的,故不支持下標(biāo)
2、集合常見操作方法
2、1 增加數(shù)據(jù)
- add()
s1 = {10, 20}
s1.add(100)
s1.add(10)
print(s1) # {100, 10, 20}
因?yàn)榧嫌腥ブ毓δ?#xff0c;所以,當(dāng)向集合內(nèi)追加的數(shù)據(jù)是當(dāng)前集合已有數(shù)據(jù)的話,則不進(jìn)行任何操作。
- update(), 追加的數(shù)據(jù)是序列。
s1 = {10, 20}
# s1.update(100) # 報(bào)錯(cuò)
s1.update([100, 200])
s1.update('abc')
print(s1)
2、2 刪除數(shù)據(jù)
- remove(),刪除集合中的指定數(shù)據(jù),如果數(shù)據(jù)不存在則報(bào)錯(cuò)。
s1 = {10, 20}s1.remove(10)
print(s1)s1.remove(10) # 報(bào)錯(cuò)
print(s1)
- discard(),刪除集合中的指定數(shù)據(jù),如果數(shù)據(jù)不存在也不會(huì)報(bào)錯(cuò)。
s1 = {10, 20}s1.discard(10)
print(s1)s1.discard(10)
print(s1)
2、3 查找數(shù)據(jù)
- in:判斷數(shù)據(jù)在集合序列
- not in:判斷數(shù)據(jù)不在集合序列
s1 = {10, 20, 30, 40, 50}print(10 in s1)
print(10 not in s1)
3、總結(jié)
-
創(chuàng)建集合
- 有數(shù)據(jù)集合
s1 = {數(shù)據(jù)1, 數(shù)據(jù)2, ...}
- 無數(shù)據(jù)集合
s1 = set()
-
常見操作
- 增加數(shù)據(jù)
- add()
- update()
- 刪除數(shù)據(jù)
- remove()
- discard()
- 增加數(shù)據(jù)