python中set集合常用方法

來源:互聯網
上載者:User

標籤:python

今天開始學習python的集合相關方法的使用:

#集合的定義:集合是無序的,不重複的資料集合

set={"123","456","11"}

#add:向集合中填加元素

Add an element to a set.
set.add(563)print(set)

#Clear:清除集合中的元素

Remove all elements from this set.

set.clear()print(set)返回空

#Copy:複製一個集合并賦值給一個新的集合

set3=set2.copy()

 

#difference():列印set中和set2不一樣的元素

set3=set.difference(set2)print(set3)

#different_update():把集合set中和set2不一樣的元素取出來並且更新到set裡面

Remove all elements of another set from this set.
set.difference_update(set2)print(set)

#discard():如果一個元素屬於該集合則刪除,如果不屬於該集合則什麼也不做

Remove an element from a set if it is a member.If the element is not a member, do nothing.set.discard("1234")print(set)

#pop():隨機刪除集合裡面的元素,如果集合為空白則報錯,建議使用discard

Remove and return an arbitrary set element.Raises KeyError if the set is empty.set.pop("11")print(set)

# Intersection:將set和set2兩個集合的交集放入集合3並列印。

Return the intersection of two sets as a new set.
set3=set.intersection(set2)print(set3)

 #intersection():將set和set2兩個集合的交集更新到set中。

Update a set with the intersection of itself and another.
set.intersection_update(set2)print(set)

 #isdisjoint():如果兩個集合沒有交集則返回true,反之如果有交集則返回false。

Return True if two sets have a null intersection
set3=.isdisjoint(set2)(set3)

#issubset():set是否是set2的子集,如果是返回True,否則返回false

Report whether another set contains this set.
=set.issubset(set2)()

#issuperset():set是否是set2的父集,如果是則返回True,如果不是則返回False.

Report whether this set contains another set.
set3=set.issuperset(set2)print(set3)

 

python中set集合常用方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.