Set Set
Set is similar to dict and is a set of keys , but does not store value. Therefore, the characteristic is disorderly, does not repeat. Basic features include elimination of duplicate elements and relationship testing . The Set object also supports the mathematical operation of the difference, intersection, difference, and symmetry.
First, define the collection
>>> S=set ([i]) >>> sset ([1, 2, 3])
To create a set, you need to provide a list as the input collection,
Note: The parameters passed in [1, 2, 3] are a list, and the displayed set ([1, 2, 3]) just tells you that this set has 1,2, 3 inside. these 3 elements, shown [] do not indicate that this is a list.
>>> s = Set ([1, 1, 2, 2, 3, 3]) >>> sset ([1, 2, 3])
Repeating elements are automatically filtered in set.
Ii. basic operation of the set
#添加元素
>>> S.add (4) >>> sset ([1, 2, 3, 4]) >>> S.add (4) >>> sset ([1, 2, 3, 4])
#删除元素Remove, if no exception is returned.
>>> S.remove (4) >>> sset ([1, 2, 3])
#删除元素, if present, delete; no exception is reported.
>>> S.discard (2) >>> sset ([1, 3])
#删除第一个元素
>>> S.pop () 1
#清空元素
>>> s.clear () >>> sset ([])
#跟新元素
>>> X=set ([' A ', ' B ', ' C ']) >>> s.update (x)//update the elements of set X into S >>> sset ([' A ', ' C ', ' B ']) >> > s.update (' 123 ')//split the incoming element into an individual incoming into the set >>> sset ([' A ', ' C ', ' B ', ' 1 ', ' 3 ', ' 2 '])
#列表转换成集合, and achieve the de-weight.
>>> list1=[1,2,2, ' A ', ' B ', ' B ']>>> s=set (list1) >>> sset ([' A ', 1, 2, ' B '])
Third, Relationship Testing
Common relationship descriptors:
& Intersection
| and set
-Difference Set
^ Symmetric difference (set minus intersection)
In is a member is true
Not in is not a member is true
Cases:
>>> S1 = set ([1, 2, 3]) >>> s2 = Set ([2, 3, 4]) >>> s3=set ([up]) #交集 >>> S1 & S2set ([ 2, 3]) or >>> s1.intersection (S2) Set ([2, 3]) #并集 >>> S1 | S2set ([1, 2, 3, 4]) or >>> s1.union (S2) Set ([1, 2, 3, 4]) #差集 >>> s1-s2set ([1]) or >>> S1.differ ence (S2) set ([1]) #对称差 >>> s1^s2 Set ([1, 4]) or >>> s1.symmetric_difference (S2) Set ([1, 4]) #子集 >>&G T S3.issubset (S1)//S3 is a subset of S1 true >>> 1 in S1true >>> 4 not in S1true
This article is from the "Network Technology" blog, please be sure to keep this source http://fengjicheng.blog.51cto.com/11891287/1927628
Python Notes--collection