python list comprehension usage

List Comprehension: List Comprehensions is a very simple but most commonly used function in python.

According to the name, you can know that the list comprehension should return the list type, which can generate the required list in the simplest and most understandable way.

Example: I need to get a list consisting of the squares of all the numbers in the list 1-100. You can use a for loop at this point:

a = []
for value in range(1, 101):
    a.append(value * value)

print(a)

  The a obtained at this time is an array composed of the square of each number in 1-100. This method is simple, but it's easier to use list comprehensions.

a = [value * value for value in range(1,101)]
print(a)

  The obtained a is exactly the same as the a in the previous method.

 

  In a = [value * value for value in range(1,101)], value * value is an expression, and the value of value comes from the for loop after the expression. Every time the for loop loops, the expression is calculated once, and finally Store the result of calculating the number of each iteration of the for loop in a list. Finally assign it to a.

 

 

In list comprehensions, multiple loops can also be used. for example:

 

a = [x * y for x in range(1,3) for y in range(3,5)]
print(a)

 The resulting result is:

[3, 4, 6, 8]

 range(1,3) is [1, 2], range(3,5) is [3, 4], x comes from range(1,3), y comes from range(3,5)

 The result is: 1*3, 1*4, 2*3, 2*4

 

 In addition, conditional judgments can also be added to the list comprehension:

a = [value * value for value in range(1, 11) if value % 2 == 0]
print(a)

# The result is:
[4, 16, 36, 64, 100]

  Add a conditional selection to the value value after the for loop. This example calculates the square of an even number from 1-10

 

 

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326565256&siteId=291194637