What is Python understanding? Why use them?

Posted by raydenl on Sun, 20 Feb 2022 18:40:18 +0100

If you are Xiaobai, this set of information can help you become a big bull. If you have rich development experience, this set of information can help you break through the bottleneck
2022web full set of video tutorial front-end architecture H5 vue node applet Video + data + code + interview questions.

As the most representative language_ Pythonic_ One of the grammar, I believe everyone has heard of or has used the list understanding method.

But do you know that there are three types of understanding in this language?

In this article, I will discuss what is_ Python_ And why they are used. I'll also discuss when using intelligible expressions can adversely affect the readability of the code.

What is understanding in Python?

In essence_ Python_ Comprehension in is a syntax used to create a new sequence by manipulating another iteration object.

In_ Python_ There are four types of comprehension.

  1. List understanding
  2. Dict compilation
  3. Set understanding method
  4. generator comprehension

Most beginners have a common misconception about understanding, that is, the initial iteration object needs to be the same type as understanding. However, this is not the case, for example, if you are using one_ dict compiler, Then the initial iterator can also be a list.

The type mentioned in the name refers to the type of sequence returned from understanding.

Why use understanding in Python?

We use understanding in our code because it's more_ Python_ Features, but also more readable. However, in some cases, you need to be careful when using them, because sometimes they will have the opposite effect.

List understanding

List_ Understanding is_ The most common type of understanding in Python, which follows simple syntax.

# Not using conditional in list comprehension.
[<expression> for <variable> in <iterable>]

# Using standard condition in list comprehension.
[<expression> for <variable> in <iterable> if <condition>]

# Using if and else in a list comprehension.
[<expression>  if <condition> else <expression> for <variable> in <iterable>]

As we can see here, the condition is completely optional, but if you use it, it depends on whether you use it or not_ else_ Clause, it's in_ List_ The position in understanding will change.

We can also see that they are very easy to use and are quite convenient in reducing the use of for loops, making the code more concise.

The best way to master it is to play with them and understand their limitations. The following is a real use example to give you a concept.

original_list = ["hello", "and", "welcome", "to", "list", "comprehensions"]

# Not using conditional in list comprehension.
new_list = [item.capitalize() for item in original_list]
print(new_list)
# ['Hello', 'And', 'Welcome', 'To', 'List', 'Comprehensions']

# Using standard condition in list comprehension.
new_list = [item.capitalize() for item in original_list if item not in ["and", "to"]]
print(new_list)
# ['Hello', 'Welcome', 'List', 'Comprehensions']

# Using if and else in a list comprehension.
new_list = [item.capitalize() if item not in ["and", "to"] else item for item in original_list]
print(new_list)
# ['Hello', 'and', 'Welcome', 'to', 'List', 'Comprehensions']

Dict understanding

As I mentioned earlier, understanding is mentioned in the name_ Type_ It refers to the type of sequence it creates, not the type of iterator used in understanding.

head -n 10 us.txtThe syntax for a dictionary comprehension is:



new_dictionary = {<key>:<value> for <item> in <iterable> if <condition>}

Again, the conditions here are optional.

You can use it in many different scenarios. For example, imagine that you want to be able to compare the salary of employees according to their positions in the company, and you have a long list of dictionaries containing all kinds of information about each employee.

In fact, you may be able to work with it, but if you only care about the position and salary, there is a lot of information you don't need, so we can use dictionary understanding to easily create a new dictionary containing only the information we want.

employee_list = [
    {
        'name': 'Peter',
        'surname': 'Pan',
        'position': 'Full-stack Developer',
        'salary': 60000
    },
    {
        'name': 'Molly',
        'surname': 'Weasley',
        'position': 'Front-End Developer',
        'salary': 50000
    },
    {
        'name': 'Harry',
        'surname': 'Potter',
        'position': 'Data Scientist',
        'salary': 55000
    },
    {
        'name': 'Hermione',
        'surname': 'Granger',
        'position': 'Data Engineer',
        'salary': 50000
    },
    {
        'name': 'Ronald',
        'surname': 'Weasley',
        'position': 'Junior Developer',
        'salary': 40000
    }
]

# Dict Comprehension without condition.

position_dict = {position['position']: position['salary'] for position in employee_list}
print(position_dict)
# {'Full-stack Developer': 60000, 'Front-End Developer': 50000, 'Data Scientist': 55000, 'Data Engineer': 50000, 'Junior Developer': 40000}

# Dict Comprehension with condition.

position_dict = {position['position']: position['salary'] for position in employee_list if "Developer" in position['position']}
print(position_dict)
# {'Full-stack Developer': 60000, 'Front-End Developer': 50000, 'Junior Developer': 40000}

As you can see above, we can achieve this goal very easily and cleanly in one line with the understanding of a dictionary **

Set understanding

_ Assemble_ Functions and of understanding_ List_ The understanding is similar, but it has all the advantages of the set, that is, the items in the set cannot be repeated, and the values are not arranged in order.

In addition to using curly braces instead of square brackets, it also uses_ List_ Understand similar grammar.

# Not using conditional in set comprehension.
{<expression> for <variable> in <iterable>}

# Using standard condition in set comprehension.
{<expression> for <variable> in <iterable> if <condition>}

# Using if and else in a set comprehension.
{<expression>  if <condition> else <expression> for <variable> in <iterable>}

In some cases, this may be useful, but you must remember to be careful, because if you need to sort the results, the favorable aspects of the collection can cause problems, as shown below.

original_list = ["hello", "and", "welcome", "to", "set", "comprehensions", "set", "comprehensions"]

# Not using conditional in set comprehension.
new_set = {item.capitalize() for item in original_list}
print(new_set)
# {'To', 'Hello', 'Set', 'And', 'Welcome', 'Comprehensions'}

# Using standard condition in set comprehension.
new_set = {item.capitalize() for item in original_list if item not in ["and", "to"]}
print(new_set)
# {'Set', 'Comprehensions', 'Hello', 'Welcome'}

# Using if and else in a set comprehension.
new_set = {item.capitalize() if item not in ["and", "to"] else item for item in original_list}
print(new_set)
# {'Hello', 'Set', 'and', 'to', 'Welcome', 'Comprehensions'}

Generator understanding method

Generator_ Understanding is that we are_ The least known type of understanding in Python.

_ Generator_ Is a function that returns an object (iterator). We can iterate one by one. It is a unique syntax in Python. It is usually generated by a function with the yield keyword.

The syntax of the generator is as simple as all other syntax.

# Not using conditional in generator comprehension.
(<expression> for <variable> in <iterable>)

# Using standard condition in generator comprehension.
(<expression> for <variable> in <iterable> if <condition>)

# Using if and else in a generator comprehension.
(<expression>  if <condition> else <expression> for <variable> in <iterable>)

The advantage of using the generator is that we can iterate it step by step by using the built-in function * * next() *.

generator = (i*2 if i%2 else i**2 for i in range(0,10))
for _ in range(10):
    print(next(generator), end=' ')
    
# 0 2 4 6 16 10 36 14 64 18 

When should compilers not be used?

After reading all the content here, it doesn't seem necessary to consider always using comprehension, right?

It's not.

The understanding formula in python can create readable code in all the above ways, but when we use_ Nesting_ We need to be careful when understanding the expression, because it may lead to poor readability of the code.

Nested comprehension

_ Nesting_ Formal understanding is a term that we use to refer to understanding in other understandings.

Although this is a very powerful function, it will also have the opposite effect in terms of readability.

For example, both of the following scripts create the following pyramid.

# method 1

for row in range(0, number_of_rows):
    for _ in range(0, row + 1):
        print("#", end='')
    print("
")    
    
# Method 2

print('
'.join([''.join(['#' for _ in range(1, row + 1)]) for row in range(0, number_of_rows)]))



#
##
###
####
#####
######
#######

We can see that although this is a fairly basic example, it has high readability without nested understanding, and with the increase of complexity, it is more difficult to maintain readability with these.

Through this article and understanding, we can't fully understand the power they bring to language, but at the same time, we need to be careful not to abuse them, because when logic is not simple, it will soon have an adverse impact on readability.

Whenever I begin to nest my understanding, I always like to remember this simple sentence.

Code should interpret comments, not comments.

Then decide whether it's best to write logic instead of understanding.

The advantage of using understanding is that if used properly, it can help you produce efficient readable code.

I hope you enjoy reading and continue your study

Finally, I'll share a full set of Python learning materials to help those who want to learn Python!

1, Python learning routes in all directions

All directions of Python is to sort out the commonly used technical points of Python and form a summary of knowledge points in various fields. Its purpose is that you can find corresponding learning resources according to the above knowledge points to ensure that you learn more comprehensively.

2, Learning software

If a worker wants to do well, he must sharpen his tools first. The commonly used development software for learning Python is here, which saves you a lot of time.

3, Full set of PDF e-books

The advantage of books lies in the authority and sound system. At the beginning of learning, you can only watch videos or listen to someone's lectures, but after you finish learning, you think you have mastered it. At this time, it is suggested to read books. Reading authoritative technical books is also the only way for every programmer.

4, Getting started video

When we watch videos, we can't just move our eyes and brain without hands. The more scientific learning method is to use them after understanding. At this time, the hand training project is very suitable.

5, Actual combat cases

Optical theory is useless. We should learn to knock together and practice, so as to apply what we have learned to practice. At this time, we can make some practical cases to learn.

6, Interview materials

We must learn Python in order to find a high paying job. The following interview questions are the latest interview materials from front-line Internet manufacturers such as Alibaba, Tencent and byte, and Alibaba boss has given authoritative answers. After brushing this set of interview materials, I believe everyone can find a satisfactory job.

If necessary, you can scan the CSDN official authentication QR code below on wechat and get it for free

Topics: Python Front-end html Back-end Interview