1.set (Collection)
Set is similar to Dict and is a set of keys, but does not store value. Because key cannot be duplicated, there is no duplicate key in set.
The set is the same as the concept of set in our mathematics, and it also has the concepts of intersection, set, difference set and symmetric difference set.
1.1 Define a collection you need to provide a list as a parameter, or you can create an empty collection without passing arguments
>>> s = Set ([1, 2, 2, 3]) >>> S{1, 2, 3} # You can see that the duplicate elements have been removed for us during the creation of the collection object pair >>> s = Set () set ()
1.2set Common methods
# python3.x dir (set) # [' __and__ ', ' __class__ ', ' __contains__ ', ' __delattr__ ', ' __dir__ ', ' __doc__ ', ' __eq__ ', ' __format__ ', ' __ge__ ', ' __ getattribute__ ', ' __gt__ ', ' __hash__ ', ' __iand__ ', ' __init__ ', ' __init_subclass__ ', ' __ior__ ', ' __isub__ ', ' __iter__ ', ' __ixor__ ', ' __le__ ', ' __len__ ', ' __lt__ ', ' __ne__ ', ' __new__ ', ' __or__ ', ' __rand__ ', ' __reduce__ ', ' __reduce_ex__ ', ' __ Repr__ ', ' __ror__ ', ' __rsub__ ', ' __rxor__ ', ' __setattr__ ', ' __sizeof__ ', ' __str__ ', ' __sub__ ', ' __subclasshook__ ', ' __ Xor__ ', ' Add ', ' clear ', ' copy ', ' Difference ', ' difference_update ', ' discard ', ' intersection ', ' intersection_update ', ' Isdisjoint ', ' issubset ', ' issuperset ', ' Pop ', ' Remove ', ' symmetric_difference ', ' symmetric_difference_update ', ' union ', ' Update ']
s = Set ([1, 2, 3]) S.add (4)print(s)""" adds a new element if the element already exists, There will be no action on add an element to a set . This have no effect if the element is already present. """ # Output {1, 2, 3, 4}
add Element
s = Set ([1, 2, 3]) s.clear ()print(s) "" " Delete all elements Return:none "" "# Output set ()
Clear Empty collection
A = Set ([1, 2, 3= Set ([2, 3, 4])print(a.difference (B)) "" " Find the difference between the current difference set and another set return: Difference set return the difference of the or more sets as a new set . """ # output {1}
Difference Difference Set
A = set ([1, 2, 3= Set ([2, 3, 4]) a.difference_update (B)print(A) "" " Removing all elements that exist in another collection from the current collection is actually equivalent to the value returned by the difference to the current set , which can be understood as a = a- B, or a-= "" " # output Set a result is {1}
difference_update Difference Set
A = Set ([1, 2, 3]) A.discard (2)print(a) # Output {1, 3}A.discard (4) Print(A) # Output {1, 3} "" if this element is present in a collection, it is deleted, otherwise nothing is done Remove an element from a set if it is a member. If the element is not a member, does nothing. """
discard removing elements from the collection
Python Basics (6)---set, collections Introduction