The role of the collection
Knowledge Point review: mutable types are non-hash types, immutable types are hash types
function: de-weight, relational operation
Definition: Can contain multiple elements, separated by commas, the elements of the collection follow three principles:
1. Each element must be an immutable type (hash, which can be used as a dictionary key)
2. No duplicate elements
4. Unordered
Note that the purpose of the collection is to store different values together, and to do relational operations between different sets, without having to tangle the individual values in the collection
Second, common methods
#!/usr/bin/python3Student= {'Tom','Jim','Mary','Tom','Jack','Rose'} Print(student)#output set, duplicate elements are automatically removed #member Testif('Rose' inchstudent):Print('Rose in the collection')Else : Print('Rose is not in the collection.') #set can perform set operationsA = set ('Abracadabra') b= Set ('Alacazam') Print(a)Print(A-B)#the difference between A and B Print(A | b)#the set of A and B Print(A & B)#intersection of A and B Print(a ^ b)#elements in A and b that do not exist at the same time| and set (Print(Pythons.union (LINUXS)))& Intersection (Print(Pythons.intersection (LINUXS)))SubtractionPrint(Pythons.difference (LINUXS)))^ Symmetric difference Set (Print(Pythons.symmetric_difference (LINUXS)))>,>=, <,<= parent set (Issuperset), subset (Issuberset)Set Method1:add method Add, add variable data type also will be error
s = {1,2,5,5,'g','h'}s.add (3) Prin (s)
Results:
{1, 2, 3, 5, ' H ', ' G '}
2:clear empty set 3:intersection intersection, equivalent to &
s = {1,7,9= {1,9,5}print(s&s1)print( S.intersection (S1)) Result: {9, 1} {9, 1}
4:union set, equivalent to |
s = {1,7,9= {1,9,5} print(s| S1) print(s.union (S1)) Result: {1,5,7,9} {1,5,7,9}
5:difference difference set, equivalent to-
s = {1,7,9} = {1,9,5print(S-s1 )print( S.difference (S1)) Result: {7} {7}
6:symmetric_difference cross complement set, equivalent to ^
s = {1,7,9} = {1,9,5} print(s^s1) print(s.symmetric_ Difference (S1)) Result: {5, 7} {5, 7}
7:difference-update Differential Set Update
8:isdisjoint determine if there is a intersection: 9:issubset to determine if it is a subset
s1={1,2} s2={1,2,3} print(s1.issubset (S2)) Print(S2.issubset (S1)) results: TrueFalse
10: Delete
s = {9,'SB', 1, 2, 3, 4, 5, 6} s.pop ()#Pop cannot specify delete, only can be deleted randomlyPrint(s) s.remove (4)#Specifies delete element, when deleted element does not exist, delete will errorPrint(s) s.discard (5)#the specified element is removed, and remove is the only difference that no error is presentPrint(s) Result: {2, 3, 4, 5, 6, 9,'SB'}{2, 3, 5, 6, 9,'SB'}{2, 3, 6, 9,'SB'}
Python data type five (collection)