The essence of Python that you don't know

Preface

The text and pictures in this article are from the Internet and are for learning and communication purposes only. They do not have any commercial use. If you have any questions, please contact us for processing.

PS: If you need Python learning materials, you can click on the link below to get it yourself

Python free learning materials and group communication answers Click to join


And which he compared to the programming language, Python is what kind of style? Many programmers will say indentation. Indeed, indentation is a hallmark feature of the Python language, but this is only external and formal. From the perspective of language features, what are the features of Python? I tried to search on Zhihu, and the most representative answers are four items: simple syntax, easy to learn, efficient code, and powerful functions. After carefully savoring these four items, I still feel that this is the use effect or user experience of the Python language, and it is still not a feature of the language feature level.

  • In other words, what are the language features of Python that make people generally believe that Python has the characteristics of concise syntax, easy to learn, efficient code, and powerful functions? I personally think that this is due to the "four kings" of lists, dictionaries, tuples, and sets. Although integer (int), floating-point (float) and string (str) are also important, the differences between these three objects compared to other programming languages ​​are not as obvious as the "Four King Kong". It is no exaggeration to say that lists, dictionaries, tuples, and sets represent the core and foundation of the Python language, as well as the essence of Python. Learning to use lists, dictionaries, tuples and sets means mastering the programming language of Python.
  • If you agree with this view, then the essence of Python will evolve from the "Four King Kong" of lists, dictionaries, tuples, and sets to the "bracket family" consisting of square brackets, curly brackets, and parentheses.

1. Square brackets

Square brackets are almost the first symbol in all programming languages. The first here is not the frequency of use, but the connotation and creativity of the programming language displayed by this symbol. In fact, in terms of the frequency of use of symbols, square brackets may also be ranked first-just my intuition, and there is no statistical support.

1.1 Create a list

For starters, the most common way to create a list is to use square brackets.

 

 

Even veterans will use square brackets a lot to create lists, especially when using comprehensions to create lists.

 


But I always feel that square brackets are like colloquial or slang terms, too casual. I prefer to use strict list() to create lists. Using list() to create a list is the standard method of instantiation of the list class. You can experience how the constructor of the list class adapts to different types of parameters.

1.2 Index of the list

Square brackets can create lists, but square brackets are not equivalent to lists, because square brackets are also used for indexing.

 

 

The index of the list is very flexible, especially the introduction of negative index, using -1 to indicate the last element or reverse order, it is really happy. The above operation is a common index method. If you can read the following code, it means that you have enough deep skills.

 

1.3 List method

If the method for list objects is easy to come by, then you are a Python master.

 

2. Braces

The curly braces represent dictionary objects, which most beginners think. However, this is wrong, at least one-sided. In the following code, both a and b are objects created with curly braces, but one is a dictionary and the other is a collection.

 

 

It turns out that Python uses curly braces to represent two kinds of objects: dictionaries and collections: empty or key-value pairs in curly braces represent dictionaries; curly braces without repeated elements represent collections. In order not to cause misunderstandings, I am used to using dict() to generate dictionaries and set() to generate sets.

 


In coding practice, although collections are irreplaceable in some cases, the frequency of usage of collections is the lowest among the "Four King Kong". We will not discuss them here, but only talk about the use of dictionaries.

2.1 Determine whether a key exists in the dictionary

In the Py2 era, the dict object used to have a has_key() method to determine whether it contains a key. Py3 discards this method. To judge whether a key exists in the dictionary, you can only use the in method.

 

2.2 Add a new key or update key value to the dictionary

Many people like to use the method of assigning a key to the dictionary to add a new key or update the key value to the dictionary.

 

 

I don't recommend this way. It is more ritual to use update(), and you can add or modify multiple keys at once.

 

2.3 Get a key value from the dictionary

a['age'] is the most commonly used method, but there are also exceptions where the key does not exist. The following method is recommended.

>>> a.get('age', 18)
18

2.4 Get all keys, all values, and all key-value pairs of the dictionary

The dict class provides three methods: keys(), values(), and items() to return all keys, all values, and all key-value pairs of the dictionary, respectively. It should be noted that the returned result is not a list, but an iterator. If you need the returned result in the form of a list, please use the list() conversion.

 

2.5 Iterating over the dictionary

When traversing the dictionary, many students may write keys() for traversing the dictionary. In fact, it doesn't need to be so troublesome, it can be traversed directly like the following.

 

3. Parentheses

The parentheses represent tuple objects, so there should be no problem, right? Indeed, it sounds no problem, but in the use of tuples, I believe that every beginner will fall into the same pit at least once.

3.1 The shallow pit that must be entered

The most significant feature of tuples not used in lists is that they cannot update the value of the element. If you forget or ignore this, you will fall into the pit.

 

3.2 The must-go pit

After using Python for many years, the worst bug I ever wrote is the following piece of code.

>>> import threading
>>> def do_something(name):
        print('My name is %s.'%name)

>>> th = threading.Thread(target=do_something, args=('xufive'))
>>> th.start()
Exception in thread Thread-1:
Traceback (most recent call last):
  File "C:\Users\xufive\AppData\Local\Programs\Python\Python37\lib\threading.py", line 926, in _bootstrap_inner
    self.run()
  File "C:\Users\xufive\AppData\Local\Programs\Python\Python37\lib\threading.py", line 870, in run
    self._target(*self._args, **self._kwargs)
TypeError: do_something() takes 1 positional argument but 6 were given

I clearly provided only 1 parameter, but I was prompted that 6 parameters were given. Why? It turns out that when tuple is initialized, if there is only a single parameter, a comma (,) must be added after the single parameter, otherwise, the initialization result will only return the original parameter.

>>> a = (5)
>>> a
5
>>> type(a)
<class 'int'>
>>> b = ('xyz')
>>> b
'xyz'
>>> type(b)
<class 'str'>
>>> a, b = (5,), ('xyz',)
>>> a, b
((5,), ('xyz',))
>>> type(a), type(b)
(<class 'tuple'>, <class 'tuple'>)

3.3 Single star unpacked tuple

When formatting the output string, the C language style is my favorite. When there are multiple %s that need to be matched, the following may be the most natural way of writing.

>>> args = (95,99,100)
>>> '%s:语文%d分,数学%d分,英语%d分'%('天元浪子', args[0], args[1], args[2])
'天元浪子:语文95分,数学99分,英语100分'

Correct is correct, but not exciting enough. The full marks should be written like this.

>>> args = (95,99,100)
>>> '%s:语文%d分,数学%d分,英语%d分'%('天元浪子', *args)
'天元浪子:语文95分,数学99分,英语100分'

3.4 Why use tuples?

Since the elements of a tuple cannot be changed, why use a tuple? Wouldn't it be more convenient to use lists instead of tuples? It is true that in most cases, a list can be used instead of a tuple, but the following example can prove that a list cannot replace a tuple.

>>> s = {1,'x',(3,4,5)}
>>> s
{1, (3, 4, 5), 'x'}
>>> s = {1,'x',[3,4,5]}
Traceback (most recent call last):
  File "<pyshell#32>", line 1, in <module>
    s = {1,'x',[3,4,5]}
TypeError: unhashable type: 'list'

We can add tuples to the collection, but lists cannot, because lists are unhashable. It is not difficult to understand this: list elements can be dynamically changed, so there is no fixed hash value-this conflicts with the uniqueness of the elements required by the set; and the elements of the tuple are forbidden to be updated, and the hash value is The entire life cycle will not change, so it can become an element of the collection.
Obviously, tuples and lists have completely different storage methods. Because there is no need to consider the update problem, the speed performance of tuples is much better than that of lists. Giving priority to tuples should become a basic principle followed by Python programmers.

Guess you like

Origin blog.csdn.net/pythonxuexi123/article/details/112908054