1.Set type: A set type is a collection that represents a set of objects that are unordered to each other , and the elements are unique .
The arithmetic operation of a set consists of a set, a intersection, a complement, and so on. There are two types of collections: normal sets and immutable collections. the common set supports the operations of intersection, set and complement after initialization, and cannot be changed after initialization of immutable sets.。2. Type definition in Python, the normal and immutable collections are defined by the keyword set and Frozenset , and the method of initializing the contents of the collection is to pass them to the variables of the sequence type cluster. 3. Built-in functionsThe set type has its own set of built-in functions for adding, deleting, and changing collections. Add (): Add new Element
# Create an empty collection s = set ()# Add new elements to the collection S.add ('Simon') S.add ( 111)print(s)
Update (SEQ): The collection is updated with a sequence, and each element of the sequence is added to the collection.
s = set () s.update ([1, 2, 3])print(s) #{1, 2, 3}
Remove (Element): Delete elements
s = {"Simon""Hangzhou"}s.remove (" Simon")print(s) #Hangzhou
Clear (): Clear Collection
s = {"Simon""Hangzhou"}print(s) # {' Simon ', ' Hangzhou '} s.clear ()print(s) # set ()
4. The set set () element is unordered and does not allow duplication:
Create an empty collection S=set () s={} Creates an empty dictionary by default5. Intersection intersection (), Difference set difference (), Union set ()difference ():
s = {"Simon","Hangzhou", 24}s1= {"Button","Shanghai", 24}#compare elements in s that are not present in the S1, and assign different elements to the new variable, that is, the difference setDS =s.difference (S1)Print(DS)#{"Simon", "Hangzhou"}Print(s)#{"Simon", "Hangzhou",
Difference_update ():
s = {"Simon","Hangzhou", 24}s1= {"Button","Shanghai", 24}#compare elements in s that are not present in S1, and update S to a collection of non-existent elementsPrint(s)#{"Simon", "Hangzhou",s.difference_update (S1)Print(s)#{"Simon", "Hangzhou"}
Intersection ():
s = {"Simon""Hangzhou", += {"button "Shanghai", "# ", intersection intersection () inter = s.intersection (S1)print(inter) #{$}
Union ():
s = {"Simon""Hangzhou", += {"button "Shanghai", "# " and Union ()un = s.union (S1) Print (un) # {' Simon ', ' Hangzhou ', ' Shanghai ', ' button '}
A collection of Python learning