標籤: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集合常用方法