Python 集合常用方法總結

來源:互聯網
上載者:User

標籤:mil   區別   value   16px   一個   amp   總結   pop   pos   

資料類型:int/str/bool/list/dict/tuple/float/set   (set類型天生去重)

一、集合的定義

s = set()  #定義空集合

s = {‘a‘,‘b‘,‘c‘,‘d‘}   #集合不是key-value  形的,無冒號

集合是無序的,沒辦法通過下標取值

二、集合賦值

s.add()

s = {‘a‘,‘b‘,‘c‘,‘d‘}
s.add(‘ijk‘) #注意add 與 update 的區別
# s.update(‘fgh‘)
print(s)

輸出結果:

{‘d‘, ‘ijk‘, ‘c‘, ‘b‘, ‘a‘}

s.update()

輸出結果:

{‘f‘, ‘b‘, ‘g‘, ‘d‘, ‘a‘, ‘c‘, ‘h‘}

s = set()

s = set(‘cheeseshop‘)
print(s)

輸出結果:

{‘s‘, ‘e‘, ‘p‘, ‘h‘, ‘o‘, ‘c‘}

三、刪除集合元素

s.remove()
s = set(‘cheeseshop‘)
s.remove(‘er‘) # 刪除不存在的會報錯
s.remove(‘e‘)
print(s)

s.pop()  #隨機刪除一個

 

s.discard(‘er‘)  #如果刪除的元素存在,刪除,不存在不做處理

 

del s  # 刪除集合

四、集合常用操作

s -= set(‘copy‘)   等價於  s = s - set(‘copy‘)  

取交集   

s.intersection(s1)   等價於  s & s1

取並集

s.union(s1)   等價於  s | s1 

取差集

s.difference(s1)   等價於  s - s1


  

Python 集合常用方法總結

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.