Set is unordered, cross-specific
I. Establishment of a set
Empty collection
S=set () s={} #这样默认为是一个空字典
The elements within the collection are hash-immutable data types
S={1,2,3,4}s=set ([1,2,3,4])
S=set (' python ')
Print (s) #{' h ', ' y ', ' t ', ' n ', ' P ', ' O '}
Two. Adding elements
S=set ([1,2,3,4]) S.add (5) print (s) #{1,2,3,4,5}
Update can add multiple elements
S.update ([5,6]) print (s) #{1, 2, 3, 4, 5, 6}s.update ([7,8],{9,10}) print (s) #{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
Three. Deleting an element
Both discard and remove can represent the deletion of an element, but if the element is not in the collection, using remove will cause an error, and discard will not
S={1,2,3,4}s.remove (1) print (s) #{2, 3, 4}s.discard (2) print (s) #{3, 4}s.discard (5) S.remove (5) #这句会报错
Pop
S={1,2,3,4}a=s.pop () #随机删除一个元素并将其作为返回值
Print (a)
Clear
S.clear () #清空集合print (s) #set () empty collection
Four. Immutable set Frozenset
S=frozenset (1,2,3,4) #不能进行增加或删除等操作
Five. The relationship between collections
S1=set ([1,2,3,4,5]) S2=set ([4,5,6,7,8])
Intersection
S3=s1&s2print (S3) #{4,5}s3=s1.intersection (S2) print (s3) #{4,5}
and set
S3=s1|s2print (S3) #{1, 2, 3, 4, 5, 6, 7, 8}s3=s1.union (S2) print (S3) #{1, 2, 3, 4, 5, 6, 7, 8}
Subtraction
#属于s1但不属于s2s3 =s1-s2print (S3) #{1, 2, 3}s3=s1.difference (S2) print (S3) #{1, 2, 3}
Symmetry difference
#除去s1和s2中相同的元素s3 =s1^s2print (S3) #{1, 2, 3, 6, 7, 8}s3=s1.symmetric_difference (S2) print (S3) #{1, 2, 3, 6, 7, 8}
Subset
S1={1,2,3,4}s2={3,4,5,6}s3={2,3,4}print (S2<S1) #Falseprint (S3<S1) #Trueprint (S3.issubset (S1)) #True
Hyper-Set
S1={1,2,3,4}s2={3,4,5,6}s3={2,3,4}print (S1>S2) #Falseprint (S1>S3) #Trueprint (S1.issuperset (S3)) #True
Python Basic Learning----Collection