
Dictionary Dictionaries：increase Delete check change Other Circular printing

Sets aggregate：intersection Difference set Union subset Parent set Symmetric difference set increase Delete check Comparison of setsList weight
1.Dictionary Dictionaries
Dictionary (dictPython‘key’‘value’:,{}).
dict value key key Data types must be fixed and immutable, such as numbers, strings, tuples, etc. value Python data type. The example of the demonstration is as follows:
math_score = {'Madonna': 89, 'Cory': 99, 'Annie': 65, 'Nelly': 89} #Create a class of Math Grade dictionaries math
print(math_score) #{'Madonna': 89, 'Cory': 99, 'Annie': 65, 'Nelly': 89}
demo_1 = {'Madonna': 89, 1: 'iennvv', 1.34: {'Madonna': 89}, ("ifne", "fjie"): [1, 2, 3]}
print(demo_1) #{'Madonna': 89, 1: 'iennvv', 1.34: {'Madonna': 89}, ('ifne', 'fjie'): [1, 2, 3]}
demo_2 = {'Madonna': 89, {'iem': "ofem"}:99} #TypeError: unhashable type: 'dict'
demp_3 = {[1, 2, 3]: 45} #TypeError: unhashable type: 'list'
at this time we already know how to create a correct dictionary, although the length of the dictionary is a little miserably seen, but it has been a normal dictionary that can implement the function of the index dictionary.We should further contact it from four aspects: “increase”, “delete”, “check” and “change”.
“Increase:stayPython“, we can add functions to the dictionary in three ways: the first is to add directly through the dictionary name and the middle brackets. = Connect the value value can also be passed through key value setdefault() , if input key ” exists in the dictionary, regardless of the input. value is correct or not (also can not lose), return to return key ” in the song body, if key does not exist in the dictionary, it will put the brackets inside. key valueIf there is no value, the default value is none update() The combination of two dictionaries is implemented (if the key value pairs are intersected in two dictionaries, if not, then added to the original dictionary). The concrete examples are as follows:
math_score = {'Madonna': 89, 'Cory': 99, 'Annie': 65, 'Nelly': 89} #Create a class of Math Grade dictionaries math
math_score['Baade'] = 77 #Add a key value to'Baade': 77
print(math_score) #{'Madonna': 89, 'Cory': 99, 'Annie': 65, 'Nelly': 89, 'Baade': 77}
print(math_score.setdefault('Madonna')) #89
print(math_score.setdefault('Madonna', 22)) #89
math_score.setdefault('Aine') #'Aine' There is no new key value in the dictionary, because no value is set, and the default is none.
print(math_score) #{'Madonna': 89, 'Cory': 99, 'Annie': 65, 'Nelly': 89, 'Baade': 77, 'Aine': None}
math_score.setdefault('Mary', 100) #'Mary' In the absence of a dictionary, the new key value pair
print(math_score) #{'Madonna': 89, 'Cory': 99, 'Annie': 65, 'Nelly': 89, 'Baade': 77, 'Aine': None, 'Mary': 100}
g = {1:2, 3:4, 'Madonna': 89} #Build a new dictionary G
math_score.update(g) #The new dictionary, G, is incorporated into the original dictionary math_score
print(math_score) #{'Madonna': 89, 'Cory': 99, 'Annie': 65, 'Nelly': 89, 'Baade': 77, 'Aine': None, 'Mary': 100, 1: 2, 3: 4}
def setdefault(self, k, d=None): # real signature unknown; restored from __doc__ """ D.setdefault(k[,d]) > D.get(k,d), also set D[k]=d if k not in D """ pass def update(self, E=None, **F): # known special case of dict.update """ D.update([E, ]**F) > None. Update D from dict/iterable E and F. If E is present and has a .keys() method, then does: for k in E: D[k] = E[k] If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v In either case, this is followed by: for k in F: D[k] = F[k] """ pass
setdefault() update() Partial source code
“Delete:The same thing with lists is that there are many kinds of dictionaries.” delete “The method, only the specific content is different. Pop ()) deletes the specified key and returns the corresponding value. If the key is not found in the dictionary, it displays the KeyError error; popitem ()The key value of the print delete (returned in the form of a tuple), random return and delete a pair of keys and values in the dictionary (generally delete the end pair); clear () empty dictionary; del can delete the content of the dictionary or directly delete the dictionary (reference list). The concrete examples are as follows:
math_score = {'Madonna': 89, 'Cory': 99, 'Annie': 65, 'Nelly': 89} #Create a class of Math Grade dictionaries math
print(math_score.pop('Cory')) #99 Print and delete the value of the specified key
print(math_score) #{'Madonna': 89, 'Annie': 65, 'Nelly': 89}
print(math_score.popitem()) #('Nelly', 89) Print and delete key value pairs (returned in tuple form) randomly return and delete a pair of keys and values in the dictionary (generally delete the last pair).
print(math_score) #{'Madonna': 89, 'Annie': 65, 'Nelly': 89}
math_score.clear() #Empty dictionary
print(math_score) #{}
math_score = {'Madonna': 89, 'Cory': 99, 'Annie': 65, 'Nelly': 89}
del math_score['Madonna'] #Delete the'Madonna'in the dictionary
print(math_score) #{'Cory': 99, 'Annie': 65, 'Nelly': 89}
del math_score #Delete dictionary math_score directly
print(math_score) #NameError: name 'math_score' is not defined
def pop(self, k, d=None): # real signature unknown; restored from __doc__ """ D.pop(k[,d]) > v, remove specified key and return the corresponding value. If key is not found, d is returned if given, otherwise KeyError is raised """ pass def popitem(self): # real signature unknown; restored from __doc__ """ D.popitem() > (k, v), remove and return some (key, value) pair as a 2tuple; but raise KeyError if D is empty. """ pass def clear(self): # real signature unknown; restored from __doc__ """ D.clear() > None. Remove all items from D. """ pass
pop() popitem() clear() Partial source code
“Check “:staywordIn the code, we can query the corresponding value values by key, which is one of its most important functions. There are two methods to choose at this time: the first is to query directly through the dictionary name plus the parentheses, and if the key value exists, it returns its value value, if it exists.No KeyError error is reported; the other is to use the builtin get () directly, input key in parentheses, and return to none if key exists back to the value value. There are two other needs when we want to get the dictionary.All key requires the builtin key () to print all the key in the dictionary, or to get all the value values in the dictionary by value (). The concrete examples are as follows:
math_score = {'Madonna': 89, 'Cory': 99, 'Annie': 65, 'Nelly': 89} #Create a class of Math Grade dictionaries math
print(math_score['Madonna']) #89
print(math_score['amd']) #KeyError: 'amd'
print(math_score.get('Madonna')) #89
print(math_score.get('Madon')) #None
print(math_score.keys()) #dict_keys(['Madonna', 'Cory', 'Annie', 'Nelly'])
print(math_score.values()) #dict_values([89, 99, 65, 89])
def get(self, k, d=None): # real signature unknown; restored from __doc__
""" D.get(k[,d]) > D[k] if k in D, else d. d defaults to None. """
pass
def keys(self): # real signature unknown; restored from __doc__
""" D.keys() > a setlike object providing a view on D's keys """
pass
def values(self): # real signature unknown; restored from __doc__
""" D.values() > an object providing a view on D's values """
pass
get() keys() values() Partial source code
Note: you can also use in to directly judge whether key is in the dictionary, but it will only return to True or False.
math_score = {'Madonna': 89, 'Cory': 99, 'Annie': 65, 'Nelly': 89} #Create a class of Math Grade dictionaries math
print('Madonna' in math_score) #True
“Change “:The dictionary can only be repaired by the dictionary name plus the middle brackets.If key input error occurs, a pair of key value pairs will be created.
math_score = {'Madonna': 89, 'Cory': 99, 'Annie': 65, 'Nelly': 89} #Create a class of Math Grade dictionaries math
math_score['Madonna'] = 100 #Modify the value value of the'Madonna'in the dictionary
print(math_score) #{'Madonna': 100, 'Cory': 99, 'Annie': 65, 'Nelly': 89}
math_score['Madna'] = 88 #'Madna' Not in the dictionary, create a new key pair'Madna':88 in the dictionary.
print(math_score) #{'Madonna': 100, 'Cory': 99, 'Annie': 65, 'Nelly': 89, 'Madna': 88}
Other：item() A dictionary is converted to a list; the copy () shallow copy is similar to the function in the list, and there is no concrete statement here; fromkeys () returns a new command that has an Iterable key value and a value equal to the value, simply to create a new oneThe dictionary, the key in front of the comma, is the new dictionary, followed by the value value given by each new dictionary. The concrete examples are as follows:
math_score = {'Madonna': 89, 'Cory': 99, 'Annie': 65, 'Nelly': 89} #Create a class of Math Grade dictionaries math
d = math_score.items() #Conversion to a list
print(d) #dict_items([('Madonna', 89), ('Cory', 99), ('Annie', 65), ('Nelly', 89)])
b = math_score.copy() #Shallow copy
print(b) #{'Madonna': 89, 'Cory': 99, 'Annie': 65, 'Nelly': 89}
c = math_score.fromkeys([1, 2, 3], 'text') #Produce a new dictionary
print(c) #{1: 'text', 2: 'text', 3: 'text'}
e = math_score.fromkeys([1, 2, 3], ['111', 'ss', 'sss'])
print(e) #{1: ['111', 'ss', 'sss'], 2: ['111', 'ss', 'sss'], 3: ['111', 'ss', 'sss']}
def items(self): # real signature unknown; restored from __doc__ """ D.items() > a setlike object providing a view on D's items """ pass def copy(self): # real signature unknown; restored from __doc__ """ D.copy() > a shallow copy of D """ pass def fromkeys(*args, **kwargs): # real signature unknown """ Returns a new dict with keys from iterable and values equal to value. """ pass
item() copy() fromkeys() Partial source code
Note: there is a small pit in fromkeys (). When the key value in the previous list is repeated, it defaults to delete the excess (key is unique), and it will not be wrongly reported. Of course, how does this belong to a pit? This is only one of the internal optimizations in Python.What I call the pit is that when fromkeys () is used to produce a new dictionary, its value value also belongs to one kind.“Shallow copy” modifies the value value of a key pair, and the other value values change with each other.
math_score = {'Madonna': 89, 'Cory': 99, 'Annie': 65, 'Nelly': 89} #Create a class of Math Grade dictionaries math
a = math_score.fromkeys([1, 2, 3], ['math', {'name':'Nelly'}, 120]) #Use fromkeys () to declare a new dictionary in the original dictionary.
print(a) #{1: ['math', {'name': 'Nelly'}, 120], 2: ['math', {'name': 'Nelly'}, 120], 3: ['math', {'name': 'Nelly'}, 120]}
a[1][0] = 'English' #Modify the value value of the new dictionary key to 1
print(a) #{1: ['English', {'name': 'Nelly'}, 120], 2: ['English', {'name': 'Nelly'}, 120], 3: ['English', {'name': 'Nelly'}, 120]}
We know in the list that we can print the list by slice or through for loop. Then how do we do it in the dictionary? I don’t sell it here. We can recycle printing through two simple for. Unlike the list, it is printed.We need to add the value value, otherwise it will only print key. I do not make statements about language, and use examples to show:
math_score = {'Madonna': 89, 'Cory': 99, 'Annie': 65, 'Nelly': 89} #Create a class of Math Grade dictionaries math
#The first method
for i in math_score: #Loop print out the dictionary of key
print(i) #Madonna Cory Annie Nelly
for i in math_score: #Loop print out the dictionary key value pair
print(i, math_score[i]) #Madonna 89 Cory 99 Annie 65 Nelly 89
#Second methods
for k, v in math_score.items(): #Loop print out the dictionary key value pair
print(k, v) #Madonna 89 Cory 99 Annie 65 Nelly 89
The difference: the above is much more efficient than the following, because it takes the value value out directly through the index, and the following process that converts the dictionary into a list in the process of operation obviously causes its efficiency to be reduced.
At best, let’s learn the most important point in the dictionary.A dictionary can be nested layer by layer（Unlimited number of layers, I believe you will not idle to build so many layers.
class_exam_score = { #It simply creates a three level dictionary, and the contents are somewhat repetitive. 'class_one': { 'math': { 'Madonna': 89, 'Cory': 99, 'Annie': 65, 'Nelly': 89}, 'English': { 'Madonna': 89, 'Cory': 99, 'Annie': 65, 'Nelly': 89}, 'Chinese': { 'Madonna': 89, 'Cory': 99, 'Annie': 65, 'Nelly': 89} }, 'class_two': { 'math': { 'Madonna': 89, 'Cory': 99, 'Annie': 65, 'Nelly': 89}, 'English': { 'Madonna': 89, 'Cory': 99, 'Annie': 65, 'Nelly': 89}, 'Chinese': { 'Madonna': 89, 'Cory': 99, 'Annie': 65, 'Nelly': 89} }, 'class_three': { 'math': {'Madonna': 89, 'Cory': 99, 'Annie': 65, 'Nelly': 89}, 'English': {'Madonna': 89, 'Cory': 99, 'Annie': 65, 'Nelly': 89}, 'Chinese': {'Madonna': 89, 'Cory': 99, 'Annie': 65, 'Nelly': 89} } } print(class_exam_score) #{'class_one': {'math': {'Madonna': 89, 'Cory': 99, 'Annie': 65, 'Nelly': 89}, 'English': {'Madonna': 89, 'Cory': 99, 'Annie': 65, 'Nelly': 89}, 'Chinese': {'Madonna': 89, 'Cory': 99, 'Annie': 65, 'Nelly': 89}}, 'class_two': {'math': {'Madonna': 89, 'Cory': 99, 'Annie': 65, 'Nelly': 89}, 'English': {'Madonna': 89, 'Cory': 99, 'Annie': 65, 'Nelly': 89}, 'Chinese': {'Madonna': 89, 'Cory': 99, 'Annie': 65, 'Nelly': 89}}, 'class_three': {'math': {'Madonna': 89, 'Cory': 99, 'Annie': 65, 'Nelly': 89}, 'English': {'Madonna': 89, 'Cory': 99, 'Annie': 65, 'Nelly': 89}, 'Chinese': {'Madonna': 89, 'Cory': 99, 'Annie': 65, 'Nelly': 89}}} print(class_exam_score['class_three']['English']['Madonna']) #Print the scores of'Madonna'in the three class English test
Simple three level dictionary
Two, Sets set
It’s almost over here. Let me take a breath first. In front of us, we finished the list, the tuple, the dictionary, is it feeling that we are fast fried, the two faces of square brackets, brackets and braces, not to be afraid, let the storm come more fiercely!!!!Then go into the collection of learning.
First of all, we need to know how to set up a new set: the first is to create a set directly by adding content in braces {} with comma (,); second.You can use the set () method to build an existing list (or tuple) into an unordered collection.
list_1 = [1, 3, 4, 5, 6, 66, 3, 6] #Create a list list_1
print(type(list_1)) #<class 'list'>
set_1 = set(list_1) #Convert the list list_1 to the set set_1
print(type(set_1)) #<class 'set'>
print(set_1) #{1, 2, 3, 4, 5, 6, 66, 22}
print(set((1, 2, 3, 4, 4))) #{1, 2, 3, 4} Creating a collection from a tuple
set_2 = {1, 3, 3, 4, 4, 77} #Create a set of set_2 directly
print(type(set_2)) #<class 'set'>
print(set_2) #{1, 3, 4, 5, 77}
Ah! Why is my value eaten? How did it shorten so much?? The system is still my value!!!! Don’t be excited. Don’t get excited. Calm down.
When we calm down and observe carefully, we will find thatThe value is something repeated in the list (or tuple).It seems to have found a hidden secret in the collection. It seems to haveA collection is similar to a dictionary. born to heavy” (automatically delete the duplicated part of the collection).Function, we can understand that set is a disordered and unrepeated data combination.But there is a distinct difference between sets and dictionaries. We can think of collections as key only and do not have the function of storing value.
def __init__(self, seq=()): # known special case of set.__init__ """ set() > new empty set object set(iterable) > new set object Build an unordered collection of unique elements. # (copied from class doc) """ pass
set() Partial source code
Note: collections and dictionaries are disordered (indexed by numbers), and the internal data types must be fixed and immutable.
except，The collection can also test the intersection of two sets of data, the integration, the difference set, the subset, and so on. It has the same part of the set knowledge we have learned from junior high school.
Intersection:Intersection, as the name suggests, takes two (or multiple) sets to intersect (the same) part, and then generates a new set. Here I provide two ways to intersection: first, we can use the builtin intersection () method to find the intersection of two sets.It can also directly interconnect two sets by finding the & operator. In the year of Sao, the old man saw your bone strange, and then gave you a free way to judge whether there was an intersection between the two sets isdisjoint (), but it had a bad place, it was in the two.When the set has an empty intersection, it returns to True, that is to say, return False when there is intersection.
list_1 = [1, 3, 4, 5, 6, 66, 3, 6] #Create a list list_1
set_1 = set(list_1)
set_2 = {1, 3, 3, 4, 4, 77} #Defining a set of set_2 directly
print(set_1.intersection(set_2)) #{1, 3, 4} The intersection of two sets is returned as a new set. (that is the same part in the two sets)
print(set_1 & set_2) #{1, 3, 4}
print(set_1.isdisjoint(set_2)) #False The two sets have the same part.
def intersection(self, *args, **kwargs): # real signature unknown """ Return the intersection of two sets as a new set. (i.e. all elements that are in both sets.) """ pass def isdisjoint(self, *args, **kwargs): # real signature unknown """ Return True if two sets have a null intersection. """ pass
intersection() isdisjoint() Partial source code
Difference set:The difference between two or more sets is returned as a new set, and we can implement this function by the difference () method; the same as the intersection and the operator. To achieve it.
list_1 = [1, 3, 4, 5, 6, 66, 3, 6] #Create a list list_1
set_1 = set(list_1)
set_2 = {1, 3, 3, 4, 4, 77} #Defining a set of set_2 directly
print('set_1:', set_1) #set_1: {1, 66, 3, 4, 5, 6}
print('set_2:', set_2) #set_2: {1, 3, 4, 77}
print(set_1.difference(set_2)) #{66, 5, 6}
print(set_2.difference(set_1)) #{77}
print(set_1  set_2) #{66, 5, 6}
print(set_2  set_1) #{77}
def difference(self, *args, **kwargs): # real signature unknown
"""
Return the difference of two or more sets as a new set.
(i.e. all elements that are in this set but not the others.)
"""
pass
difference() Partial source code
Note: unlike the intersection, there is a sequential relationship between the two sets of the difference concentration, which can be understood as who subtract who, and the difference in the order of the front and back will lead to the difference of the result.
Merge:It is the same as intersection, and concentrates on the positional relation without any set. In Python, two methods are also provided to solve the set’s integration. Union () returns all the elements of different sets to form a new set; the bit operator can also use the bit operator.And) to realize it.
list_1 = [1, 3, 4, 5, 6, 66, 3, 6] #Create a list list_1
set_1 = set(list_1)
set_2 = {1, 3, 3, 4, 4, 77} #Defining a set of set_2 directly
print('set_1:', set_1) #set_1: {1, 66, 3, 4, 5, 6}
print('set_2:', set_2) #set_2: {1, 3, 4, 77}
print(set_1.union(set_2)) #{1, 66, 3, 4, 5, 6, 77}
print(set_2.union(set_1)) #{1, 66, 3, 4, 5, 6, 77}
print(set_1  set_2) #{1, 66, 3, 4, 5, 6, 77}
def union(self, *args, **kwargs): # real signature unknown """ Return the union of sets as a new set. (i.e. all elements that are in either set.) """ pass
union() Partial source code
Subsets:The issubset () method can be used to determine whether another set contains this set (whether the elements within the parentheses contain the previous element), if the inclusion is returned to the True. Image memory: in True 。
list_1 = [1, 3, 4, 5, 6, 66, 3, 6] #Create a list list_1
set_1 = set(list_1)
set_2 = {1, 3, 3, 4, 4, 77} #Defining a set of set_2 directly
print('set_1:', set_1) #set_1: {1, 66, 3, 4, 5, 6}
print('set_2:', set_2) #set_2: {1, 3, 4, 77}
set_3 = {1, 3}
print(set_1.issubset(set_2)) #False
print(set_3.issubset(set_1)) #True
print(set_1.issubset(set_3)) #False
def issubset(self, *args, **kwargs): # real signature unknown
""" Report whether another set contains this set. """
pass
issubset() Partial source code
Parent set:Issuperset () determines whether the set contains another set, that is, when the previous one is” father “, one of them returns to” son “. True 。
list_1 = [1, 3, 4, 5, 6, 66, 3, 6] #Create a list list_1
set_1 = set(list_1)
set_2 = {1, 3, 3, 4, 4, 77} #Defining a set of set_2 directly
print('set_1:', set_1) #set_1: {1, 66, 3, 4, 5, 6}
print('set_2:', set_2) #set_2: {1, 3, 4, 77}
set_3 = {1, 3}
print(set_1.issuperset(set_2)) #False
print(set_1.issuperset(set_3)) #True
def issuperset(self, *args, **kwargs): # real signature unknown
""" Report whether this set contains another set. """
pass
issuperset() Partial source code
Symmetric difference sets:The symmetric difference between the two sets is returned as a new set. Do you feel so ignorant, don’t be afraid, and I am saying that symmetric difference set is a way to take different parts of the two sets to form a new set. You can use itsymmetric_difference() Or operator ^ to implement symmetric difference sets.
list_1 = [1, 3, 4, 5, 6, 66, 3, 6] #Create a list list_1
set_1 = set(list_1)
set_2 = {1, 3, 3, 4, 4, 77} #Defining a set of set_2 directly
print('set_1:', set_1) #set_1: {1, 66, 3, 4, 5, 6}
print('set_2:', set_2) #set_2: {1, 3, 4, 77}
print(set_1.symmetric_difference(set_2)) #{66, 5, 6, 77}
print(set_1 ^ set_2) #{66, 5, 6, 77}
def symmetric_difference(self, *args, **kwargs): # real signature unknown
"""
Return the symmetric difference of two sets as a new set.
(i.e. all elements that are in exactly one of the sets.)
"""
pass
symmetric_difference() Partial source code
“Increase:add() Add a single element to the collection. If the element already exists, it will not work; update () adds multiple elements to the collection, and the result is similar to add ().
list_1 = [1, 3, 4, 5, 6, 66, 3, 6] #Create a list list_1
set_1 = set(list_1)
print('set_1:', set_1) #set_1: {1, 66, 3, 4, 5, 6}
set_1.add(7777) #Add element 7777
print(set_1) #{1, 66, 3, 4, 5, 6, 7777}
set_1.add(66) #Add element 66
print(set_1) #{1, 66, 3, 4, 5, 6, 7777}
set_1.update([1, 222, 3333]) # Add a number of
print(set_1) #{1, 66, 3, 4, 5, 6, 7777, 3333, 222}
def add(self, *args, **kwargs): # real signature unknown """ Add an element to a set. This has no effect if the element is already present. """ pass def update(self, *args, **kwargs): # real signature unknown """ Update a set with the union of itself and others. """ pass
add() update() Partial source code
“Delete:In the collection, we can choose many different ways to delete.remove() Delete the specified element in the parenthesis, if the element is not in the set, the error is reported; pop () removes the element within a set and returns the value of its deletion; discard () deletes the specified element in the parenthesis, if the element is a member of the set, remove the element from the collection.Otherwise, do nothing, return to None; the rest is clear () and del, and the usage is the same as before.
list_1 = [1, 3, 4, 5, 6, 66, 3, 6] #Create a list list_1
set_1 = set(list_1) #Convert the list to a collection
print('set_1:', set_1) #set_1: {1, 66, 3, 4, 5, 6}
set_1.remove(1) #Specifies that an element is deleted, and if there is no error, it will be reported.
print(set_1) #{66, 3, 4, 5, 6}
print(set_1.pop()) #66 #Randomly delete one and return the deleted value without adding contents in brackets.
print(set_1) #{3, 4, 5, 6}
print(set_1.discard(1)) #None #Deletes the specified value. If the specified value is not in it, it will not report error. If printed, it will only return to none.
print(set_1) #{3, 4, 5, 6}
print(set_1.discard(3)) #None
print(set_1) #{3, 4, 5, 6}
set_1.clear() #Empty set
print(set_1) #set()
del set_1 #Delete set
print(set_1) #NameError: name 'set_1' is not defined
def remove(self, *args, **kwargs): # real signature unknown
"""
Remove an element from a set; it must be a member.
If the element is not a member, raise a KeyError.
"""
pass
def pop(self, *args, **kwargs): # real signature unknown
"""
Remove and return an arbitrary set element.
Raises KeyError if the set is empty.
"""
pass
def discard(self, *args, **kwargs): # real signature unknown
"""
Remove an element from a set if it is a member.
If the element is not a member, do nothing.
"""
pass
def clear(self, *args, **kwargs): # real signature unknown
""" Remove all elements from this set. """
pass
remove() pop() discard() clear() Partial source code
In the collection, we can only judge whether an element is in the collection by in or not in.
list_1 = [1, 3, 4, 5, 6, 66, 3, 6] #Create a list list_1
set_1 = set(list_1) #Convert the list to a collection
print('set_1:', set_1) #set_1: {1, 66, 3, 4, 5, 6}
print(1 in set_1) #True
print(3 not in set_1) #False
The comparison of the set:True or False is returned by the operator < > = = comparing the relations between the two sets. It can be used to judge subsets and parent sets, similar to children and parents.
set_1 = {1, 3, 5, 777}
set_2 = {1, 3}
print(set_1 < set_2) # False
print(set_1 == set_2) # False
print(set_1 > set_2) # True
“Other “:len() Gets the length of the collection (the number of elements in the collection); copy () shallow copy.
list_1 = [1, 3, 4, 5, 6, 66, 3, 6] #Create a list list_1
set_1 = set(list_1) #Convert the list to a collection
print('set_1:', set_1) #set_1: {1, 66, 3, 4, 5, 6}
print(len(set_1)) #6
set_2 = set_1.copy() #Shallow copy
print(set_2) #{1, 66, 3, 4, 5, 6}
Three unknown east east: returns to None or reports wrong. The key is that it doesn’t play with us. I really don’t know where to use it. Welcome to discuss it together.
list_1 = [1, 3, 4, 5, 6, 66, 3, 6] #Create a list list_1
set_1 = set(list_1) #Convert the list to a collection
print('set_1:', set_1) #set_1: {1, 66, 3, 4, 5, 6}
set_2 = {1, 3, 3, 4, 4, 77}
print(set_1.intersection_update(set_2)) #None
print(set_1.difference_update(set_2)) #None
print(set_1.symmetric_difference_update(set_1)) #None
def intersection_update(self, *args, **kwargs): # real signature unknown """ Update a set with the intersection of itself and another. """ pass def difference_update(self, *args, **kwargs): # real signature unknown """ Remove all elements of another set from this set. """ pass def symmetric_difference_update(self, *args, **kwargs): # real signature unknown """ Update a set with the symmetric difference of itself and another. """ pass
intersection_update() difference_update() symmetric_difference_update() Partial source code
Extension:How to delete duplicate elements in a list when you are faced with massive list data? Here is a solution to the problem. The specific demo code is as follows:
a = [1, 2, 3, 43, 31, 2] #Create a new list
b = set(a) #Turn the list to a collection
print(b) #{1, 2, 3, 43, 31}
c = [i for i in b] #Cycle set
print(c) #[1, 2, 3, 43, 31]