Python学习:集合
生活随笔
收集整理的這篇文章主要介紹了
Python学习:集合
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
一、集合的創(chuàng)建
創(chuàng)建集合使? {} 或 set() , 但是如果要?jiǎng)?chuàng)建空集合只能使? set() ,因?yàn)?{} ?來創(chuàng)建空字典。
s1 = {10, 20} print(s1) s2 = set('abc') print(s2)二、集合的特點(diǎn)
(1)集合可以去掉重復(fù)數(shù)據(jù);
(2)集合數(shù)據(jù)是?序的,故不?持下標(biāo)
三、常用操作
(1)add()
s1 = {2, 3} s1.add(4) s1.add(2) print(s1) # {4, 2, 3}注:當(dāng)向集合內(nèi)追加的數(shù)據(jù)是當(dāng)前已有數(shù)據(jù)的話,不進(jìn)行任何操作。
(2)update(), 追加的數(shù)據(jù)是序列
(3)remove(),刪除集合中的指定數(shù)據(jù),如果數(shù)據(jù)不存在則報(bào)錯(cuò)。
s1 = {2, 3} s1.remove(2) print(s1) s1.remove(2) # 報(bào)錯(cuò) print(s1)(4)discard(),刪除集合中的指定數(shù)據(jù),如果數(shù)據(jù)不存在也不會(huì)報(bào)錯(cuò)
s1 = {2, 3} s1.remove(2) print(s1) s1.remove(2) # 不會(huì)報(bào)錯(cuò) print(s1)(5)pop(),隨機(jī)刪除集合中的某個(gè)數(shù)據(jù),并返回這個(gè)數(shù)據(jù)。
s1 = {1, 2, 3, 4, 5} num = s1.pop() print(num) print(s1)(6)in:判斷數(shù)據(jù)在集合序列;not in:判斷數(shù)據(jù)不在集合序列。
s1 = {1, 2, 3, 4, 5} print(1 in s1) print(1 not in s1)總結(jié)
以上是生活随笔為你收集整理的Python学习:集合的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python学习:字符串
- 下一篇: 邮件报文格式和MIME