Python's update set
Because set stores a set of unordered elements that are not duplicated, the update set mainly does two things:
One is to add the new element to the set, and the other is to remove the existing element from the set.
when adding an element, use the Add () method of Set :
>>> s = Set ([1, 2, 3]) >>> S.add (4) >>> print Sset ([1, 2, 3, 4])
If the added element already exists in set, add () will not error, but will not be added:
>>> s = Set ([1, 2, 3]) >>> S.add (3) >>> print sset ([1, 2, 3])
when removing elements from a set, use the Remove () method of Set :
>>> s = Set ([1, 2, 3, 4]) >>> S.remove (4) >>> print Sset ([1, 2, 3])
If the deleted element does not exist in the set, remove () will error:
>>> s = Set ([1, 2, 3]) >>> S.remove (4) Traceback (most recent): File ' <stdin> ', line 1 , in <module>keyerror:4
So with Add () can be added directly, and remove () before you need to judge.
Task
For the following set, given a list, for each element in the list, if it is in set, it is deleted, if it is not in the set, it is added.
s = set ([' Adam ', ' Lisa ', ' Paul ']) L = [' Adam ', ' Lisa ', ' Bart ', ' Paul ']
-
? What's going on?
-
Determines whether the element is in set, using the in operator.
Reference code:
s = set ([' Adam ', ' Lisa ', ' Paul ']) L = [' Adam ', ' Lisa ', ' Bart ', ' Paul ']for name in L: the if name in S: s.remove (name)
else: s.add (name) print S
Python's update set