Python set The most common operation of a collection is to add 、 Remove elements , And the intersection between sets 、 Combine 、 Subtraction and so on , This section will explain the specific implementation of these operations one by one .
set Add elements to the collection , have access to set Type provided add() Method realization , The syntax format of this method is :
setname.add(element)
among ,setname Represents the collection of elements to add ,element Represents the content of the element to be added .
It should be noted that , Use add() Method , It's just numbers 、 character string 、 Tuple or boolean type (True and False) value , Can't add list 、 Dictionaries 、 Collect this kind of variable data , otherwise Python The interpreter will report TypeError error . for example :
a = {
1,2,3}
a.add((1,2))
print(a)
a.add([1,2])
print(a)
The running result is :
{(1, 2), 1, 2, 3}
Traceback (most recent call last):
File “C:\Users\mengma\Desktop\1.py”, line 4, in
a.add([1,2])
TypeError: unhashable type: ‘list’
Delete existing set The specified element in the collection , have access to remove() Method , The syntax format of this method is as follows :
setname.remove(element)
Use this method to delete elements in the collection , It should be noted that , If the deleted element is not included in the collection , Then this method throws KeyError error , for example :
a = {
1,2,3}
a.remove(1)
print(a)
a.remove(1)
print(a)
The running result is :
{2, 3}
Traceback (most recent call last):
File “C:\Users\mengma\Desktop\1.py”, line 4, in
a.remove(1)
KeyError: 1
In the above procedure , Because of the elements in the set 1 have been deleted , So when you try to use remove() Method is deleted , May trigger KeyError error .
If we don't want to prompt the interpreter when the deletion fails KeyError error , You can also use discard() Method , This method and remove() The usage of the method is exactly the same , The only difference is , When deleting an element in a collection fails , This method does not throw any errors .
for example :
a = {
1,2,3}
a.remove(1)
print(a)
a.discard(1)
print(a)
The running result is :
{2, 3}
{2, 3}
The most common operation of a set is to intersect 、 Combine 、 Difference set and symmetric difference set operation , First of all, it is necessary to popularize the meaning of each operation .
Above picture , Yes 2 A collection of , Respectively set1={1,2,3} and set2={3,4,5}, They have the same elements , There are also different elements . Take these two sets for example , The results of different operations are shown in the following table .