Python uses dict and set

1.dict

Python has a built-in dictionary: dict is supported. The full name of dict is dictionary, which is also called map in other languages. It uses key-value storage and has extremely fast search speed.

For example, suppose you want to find the corresponding grades based on the names of your classmates. If you use a list to implement it, you need two lists:

names = ['Michael', 'Bob', 'Tracy']
scores = [95, 75, 85]

Given a name, to find the corresponding score, you must first find the corresponding position in the names, and then retrieve the corresponding score from the scores. The longer the list, the longer it takes.

If implemented with dict, only a "name"-"score" comparison table is needed, and the results are directly searched based on the name. No matter how big the table is, the search speed will not slow down. Write a dict in Python as follows:

>>> d = {
    
    'Michael': 95, 'Bob': 75, 'Tracy': 85}
>>> d['Michael']
95

Why is dict search so fast? Because the implementation principle of dict is the same as that of looking up a dictionary. Assuming that the dictionary contains 10,000 Chinese characters, we need to look up a certain word. One way is to turn the dictionary back from the first page until we find the word we want. This method is to find the element in the list. The larger the list, the slower the search.

The second method is to first look up the page number corresponding to the word in the index table of the dictionary (such as the radical table), and then directly turn to the page to find the word. No matter which word is searched, the search speed is very fast and will not slow down as the size of the dictionary increases.

The dict is the second way of implementation. Given a name, such as'Michael', dict can directly calculate the "page number" of Michael's corresponding storage scores internally, which is the memory address where the number 95 is stored, and take it out directly. So the speed is very fast.

As you can guess, this kind of key-value storage method must calculate the storage location of the value according to the key when it is put in, so that the value can be directly obtained according to the key when it is taken.

The method of putting data into the dict, in addition to the designation during initialization, can also be put into the key:

>>> d['Adam'] = 67
>>> d['Adam']
67

Since a key can only correspond to one value, if you put a key into value multiple times, the following value will erase the previous value:

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:778463939
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
>>> d['Jack'] = 90
>>> d['Jack']
90
>>> d['Jack'] = 88
>>> d['Jack']
88

If the key does not exist, dic will report an error. To avoid the error that the key does not exist, there are two ways. One is to judge whether the key exists by in:

>>> 'Thomas' in d
False

The second is through the get() method provided by dict. If the key does not exist, you can return None (note: the Python interactive environment does not display the result when None is returned). Or the value you specify:

>>> d.get('Thomas')
>>> d.get('Thomas', -1)
-1

To delete a key, use the pop(key) method, and the corresponding value will also be deleted from the dict:

>>> d.pop('Bob')
75
>>> d
{
    
    'Michael': 95, 'Tracy': 85}

It is important to note that the internal storage order of the dict has nothing to do with the order in which the keys are placed.

Compared with list, dict has the following characteristics:

  • The search and insertion speed is extremely fast, and will not slow down as the key increases;
  • Need to take up a lot of memory, a lot of waste of memory.

The opposite of list:

  • The time to find and insert increases with the increase of elements;
  • It occupies little space and wastes little memory.

Therefore, dict is a way to exchange space for time.

dict can be used in many places where high-speed search is required. It is almost everywhere in Python code. The correct use of dict is very important. The first thing to keep in mind is that the key of dict must be an immutable object.

This is because dict calculates the storage location of value according to the key. If the result of calculating the same key each time is different, the dict is completely confused. This algorithm for calculating the location by key is called a hash algorithm (Hash).

To ensure the correctness of the hash, the key object cannot be changed. In Python, strings, integers, etc. are immutable, so they can be safely used as keys. The list is variable and cannot be used as a key:

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:778463939
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
>>> key = [1, 2, 3]
>>> d[key] = 'a list'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'

2. Set

Set is similar to dict. It is also a set of keys, but does not store value. Since the key cannot be repeated, there is no duplicate key in the set.

To create a set, you need to provide a list as the input set:

>>> s = set([1, 2, 3])
>>> s
{
    
    1, 2, 3}

Note that the incoming parameter [1, 2, 3] is a list, and the displayed {1, 2, 3} just tells you that there are 3 elements of 1, 2, 3 in the set, and the order of display does not indicate The set is ordered. .

Repeated elements are automatically filtered in the set:

>>> s = set([1, 1, 2, 2, 3, 3])
>>> s
{
    
    1, 2, 3}

You can add elements to the set through the add(key) method, and you can add them repeatedly, but it will not have any effect:

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:778463939
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
>>> s.add(4)
>>> s
{
    
    1, 2, 3, 4}
>>> s.add(4)
>>> s
{
    
    1, 2, 3, 4}

Elements can be deleted through the remove(key) method:

>>> s.remove(4)
>>> s
{
    
    1, 2, 3}

Set can be regarded as a mathematically unordered and non-repetitive set of elements. Therefore, two sets can perform mathematical operations such as intersection and union:

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:778463939
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
>>> s1 = set([1, 2, 3])
>>> s2 = set([2, 3, 4])
>>> s1 & s2
{
    
    2, 3}
>>> s1 | s2
{
    
    1, 2, 3, 4}

The only difference between set and dict is that the corresponding value is not stored. However, the principle of set is the same as that of dict. Therefore, variable objects cannot be placed in the same way. Because it is impossible to judge whether two variable objects are equal, the set cannot be guaranteed. "There will be no duplicate elements" inside.
Talk about immutable objects again

As we mentioned above, str is an immutable object, and list is a mutable object.

For mutable objects, such as list, if you operate on the list, the contents of the list will change, such as:

>>> a = ['c', 'b', 'a']
>>> a.sort()
>>> a
['a', 'b', 'c']

And for immutable objects, such as str, do operations on str:

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:778463939
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
>>> a = 'abc'
>>> a.replace('a', 'A')
'Abc'
>>> a
'abc'

Although the string has a replace() method, it does change'Abc', but the variable a is still'abc' at the end, how should we understand it?

Let's first change the code to the following:

>>> a = 'abc'
>>> b = a.replace('a', 'A')
>>> b
'Abc'
>>> a
'abc'

Always keep in mind that a is a variable and'abc' is a string object! Sometimes, we often say that the content of object a is'abc', but it actually means that a itself is a variable, and the content of the object it points to is'abc'. Therefore, for an immutable object, call the object Any method of its own will not change the content of the object itself. Instead, these methods create a new object and return it, thus ensuring that the immutable object itself is always immutable.

Guess you like

Origin blog.csdn.net/sinat_38682860/article/details/109103603