I. How to construct a collection:
Set name = Set ()
1. Set () can have a parameter, the parameter type must be iterative, such as a string, a list, can be split into separate elements of the meaning
2. If the parameter is not taken, an empty set is constructed
>>> ASet = set ("ABCD") #参数为字符串 >>> aset{' C ', ' B ', ' d ', ' a '}>>> bSet = [' A ', 1.5, ' set '] #参数为普通 List >>> bset[' A ', 1.5, ' set ']>>> list = [1,1,2,2,3,3] #列表中有重复元素, building a collection with this list ignores duplicate elements >>> CSet =set (l IST) >>> Cset{1, 2, 3}>>> nullset = set () #构建空集 >>> Nullsetset ()
Two. Functions related to the collection
Len (): As with other collection types, determines the number of elements
In: Determines whether an element is in the collection, returns a Boolean value
For: Used to iterate over the elements in the collection
Three. Collection methods
The following methods are used in the same way as mathematical concepts:
Set A.intersection (set B) #判断AB集合交集
Set A.union (set B) #判断集合AB的并集
Set A.difference (set B) #判断集合A和集合B的差集
Set A.symmetric_difference (set B) #判断AB集合的对称差//ab intersection of Set-ab
Set A.issubset (set B) #判断A是否为B的子集
Set A.issuperset (set B) #判断A是否为B的超集
Other collection methods:
Set A.add (Element) #向集合A中添加元素element, no effect if present
Sets the A.clear () #删除集合A中的元素 to make it an empty set
Set A.remove (Element) #删除集合A中元素element, element does not exist will error
Set A.discard (Element) #删除集合A中元素element, element does not exist no error
Copy () #返回集合的浅拷贝
Python Learning Diary---Collection