This article is from the Mu-class network "Pyrhon"
1. Set characteristics
Determines whether an element is fast in set.
The set stored element is similar to the Dict key, and must be an immutable object , so any mutable object cannot be placed in the set.
The way to create a set is to call set () and pass in a list,list element as the set element:
>>> s = set ([' A ', ' B ', ' C ')
You can view the contents of the set:
>>> Print S
Set ([' A ', ' C ', ' B '])
Note that the above print form is similar to list, but it is not a list, and it can be seen that the order of printing and the order of the original list may be different because the elements stored inside the set are unordered .
Because set cannot contain duplicate elements, what happens when we pass in a list that contains repeating elements?
>>> s = set ([' A ', ' B ', ' C ', ' C '])
>>> Print S
Set ([' A ', ' C ', ' B '])
>>> Len (s)
3
The result shows that the set automatically removes the duplicate elements, the original list has 4 elements, but the set has only 3 elements.
Because set stores an unordered collection, it cannot be accessed through an index.
Accessing an element in a set actually determines whether an element is in the set.
For example, a set that stores the name of a class student:
>>> s = set ([' Adam ', ' Lisa ', ' Bart ', ' Paul ')
You can use the in operator to determine:
Is Bart a classmate of the class?
>>> ' Bart ' in S
True
Is bill a classmate of the class?
>>> ' Bill ' in S
False
If you create good one set beforehand, include ' MON ' ~ ' SUN ':
Weekdays = set ([' MON ', ' TUE ', ' WED ', ' THU ', ' FRI ', ' SAT ', ' SUN '])
To determine if the input is valid, just determine if the string is in set:
Because set is also a collection, traversing set is similar to traversing a list and can be implemented through a for loop.
You can iterate through the elements of a set directly using a For loop:
>>> s = set ([' Adam ', ' Lisa ', ' Bart '])
...
Note: when observing A for loop, the order of the elements and the order of the list is likely to be different when traversing 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.
>>> s = Set ([1, 2, 3])
>>> S.add (4)
>>> Print S
Set ([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 S
Set ([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 S
Set ([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 "", Line 1, in
Keyerror:4
so with Add () can be added directly, and remove () before you need to judge .
python--about Set