How to apply Python list comprehension

WBOY
Release: 2023-05-20 08:10:13
forward
1919 people have browsed it

Python list comprehension

List comprehension is a shortcut for Python to build a list (list). You can create a list using simple code.

1. range( ) function

Python's range() function can be used to create a list of integers, generally used in for loops.

range() syntax: range(start, stop[, step ])

start: Counting starts from start, the default is from 0 (closed interval), for example: range(5) is equivalent to range(0,5).

stop: Counting to the end of stop, but not including stop (open interval). For example: range(0,5) is [0, 1, 2, 3, 4], not including 5.

step: step Long, the difference between two adjacent values, the default is 1. For example: range(0,5) is equivalent to range(0, 5, 1).

Why do we need to talk about range( before the list comprehension ), because list comprehensions generate lists through an iterable object, range() can be said to be the most commonly used iterable object in list comprehensions. For list comprehensions, range() is one of the essence 1. Without range(), the readability and simplicity of list comprehension will be greatly reduced.

2. List comprehension

List comprehension refers to loop creation List.

The for loop has a very wide range of application scenarios and can also be used to create a list, and the list comprehension is equivalent to a simplified version of the for loop creating a list.

# for循环 list_a = list() for a in range(5): list_a.append(a) print(list_a)
Copy after login
# 列表推导式 list_b = [b for b in range(5)] print(list_b)
Copy after login

The above are Code for creating lists using for loops and list comprehensions. The results of list_a and list_b are the same, both [0, 1, 2, 3, 4].

Let’s look at the more complicated list comprehensions :

# in后面跟其他可迭代对象,如字符串 list_c = [7 * c for c in "python"] print(list_c) # 带if条件语句的列表推导式 list_d = [d for d in range(6) if d % 2 != 0] print(list_d) # 多个for循环 list_e = [(e, f * f) for e in range(3) for f in range(5, 15, 5)] print(list_e) # 嵌套列表推导式,多个并列条件 list_g = [[x for x in range(g - 3, g)] for g in range(22) if g % 3 == 0 and g != 0] print(list_g)
Copy after login

Run result:

['ppppppp', 'yyyyyyy', 'ttttttt', 'hhhhhhh', 'ooooooo', 'nnnnnnn'] [1, 3, 5] [(0, 25), (0, 100), (1, 25), (1, 100), (2, 25), (2, 100)] [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11], [12, 13, 14], [15, 16, 17], [18, 19, 20]]
Copy after login

Code explanation:

1. The list comprehension will traverse the following iterable objects, and then perform operations according to the expression before for, Generate the final list.

2. If there is an if conditional statement, the for traversal is followed by conditional judgment.

3. If there are multiple for loops, the final number of data is Cartesian product of multiple for loops.

4. Nested list derivation can be performed, which is the same as the principle of nested for loops.

3. Code readability

For those who are not familiar with list derivation, you can use a for loop to achieve the same function, but it requires several lines of code, while list derivation only requires one line of code.

Many people will say that the code is concise But the readability is reduced. In fact, when we are familiar with list comprehensions (we will become familiar with it after writing it a few times), the function of the code can be easily seen at a glance, but it is basically impossible to read the for loop code at a glance. Especially when the for loop that creates a list is nested in other for loops of business logic, it is precisely the use of list comprehensions that is the most readable.

At the same time, list comprehensions have their own local role in Python3 Domain, just like a function. The variables and assignments inside the expression only work locally. Variables with the same name in the context of the expression can also be referenced normally, and local variables will not affect them.

In other words, list derivation will not have the problem of variable leakage, and the assignment operation in the list derivation is unlikely to affect the variable with the same name in the list derivation context.

Of course, not all scenarios are recommended to use lists Derivation. For example: if the list derivation code exceeds two lines, you should consider changing to a for loop. List derivation that exceeds two lines is really unreadable. The general principle is to only use Use list derivation to create a new list, and try to keep it as short as possible.

4. Dictionary derivation

Since Python2.7, the concept of list derivation has been transplanted to the dictionary, thus creating dictionary derivation (You will see set derivation later).

If the concept of list derivation is already familiar to you, it is not difficult to accept dictionary derivation. Just look at the code:

# 因为key是唯一的,所以最后value都是1 dict_a = {key: value for key in 'python' for value in range(2)} print(dict_a) # 可以根据键来构造值 dict_b = {key: key * key for key in range(6)} print(dict_b) # 遍历一个有键值关系的可迭代对象 list_phone = [('HUAWEI', '华为'), ('MI', '小米'), ('OPPO', 'OPPO'), ('VIVO', 'VIVO')] dict_c = {key: value for key, value in list_phone} print(dict_c)
Copy after login

Running results:

{'p': 1, 'y': 1, 't': 1, 'h': 1, 'o': 1, 'n': 1} {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25} {'HUAWEI': '华为', 'MI': '小米', 'OPPO': 'OPPO', 'VIVO': 'VIVO'}
Copy after login

5. Set derivation

Python2.7 not only brings dictionary derivation, but also set derivation.

Similarly, let’s look at the code directly, In this way, you can intuitively see the set derivation.

# 遍历一个可迭代对象生成集合 set_a = {value for value in '有人云淡风轻,有人负重前行'} print(set_a)
Copy after login

Running results:

{'负', '有', '人', '轻', '前', '云', '重', ',', '淡', '风', '行'}
Copy after login

The set is unordered and non-repeating, so repeated elements will be automatically removed, and each run will display The order is different.

It can be summarized from the above code:

The set derivation is to replace the [] of the list derivation with {}, and the dictionary derivation is to deduce the combination of two values. It looks like a key-value pair.

In addition, whether it is a dictionary comprehension or a set comprehension, it can be followed by if conditional statements, nested loops, etc. like a list comprehension. The specifics can be based on your own Need to use.

The above is the detailed content of How to apply Python list comprehension. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!