The correct way to use Python list comprehension (1)

Let’s force two sentences first:

Python is an extremely diverse and powerful programming language! When it comes to solving a problem, it has a different approach. In this article, the list comprehension will be shown

(List Comprehension). We will discuss how to use it? When should or should not use it?
Please add image description

Advantages of list comprehension

  • Saves more time and space than loops.
  • Fewer lines of code are required.
  • Iterative statements can be converted into formulas.

How to create a list in Python

A list comprehension is a syntactic construct that creates a list from an existing list. Let's look at different implementations of creating a list

cycle

Loops are the traditional way to create lists. No matter what kind of loop you use. To create a list this way, you should:

  1. Instantiate an empty list.

  2. Loop over the elements of an iterable (such as a range).

  3. Append each element to the end of the list.

Python学习交流Q群:660193417###
numbers = []
for number in range(10):
    numbers.append(number)
    
print(numbers)

output:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

In this example, you instantiate an empty list numbers. Then use a for loop to iterate over range(10) and use the append() method to append each number to the end of the list.
Please add image description

map() object

map() is another way to create a list. You need to pass map() a function and an iterable, and it will create an object. This object contains the output obtained by executing each iterated element using the specified function.

For example, we will present the task of adding VAT to the price of certain products.

VAT_PERCENT = 0.1  # 10%
def add_vat(price):
    return price + (price * VAT_PERCENT)
Python学习交流Q群:660193417###
prices = [10.03, 8.6, 32.85, 41.5, 22.64]
grand_prices = map(add_vat, prices)
print(grand_prices)
gra

You have built the add_vat() function and created the prices iterable object. You pass both arguments to map() and collect the resulting map object

grand_prices, or you can easily convert it to a list using list().

output:

<map object at 0x7f18721e7400>  # map(add_vat, prices)
[11.03, 9.46, 36.14, 45.65, 24.9]  # list(grand_prices)

list comprehension

Now, let's look at the list-comprehension-style approach! This is really Pythonic, and a better way to create lists. To see how powerful this approach is, let's rewrite that looping example with a single line of code.

numbers = [number for number in range(10)]
print(numbers)

output

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

As you can see, this is an incredible approach! The list comprehension looks readable enough that you don't need to write more code, just one line.

For a better understanding of lists, take a look at the following syntax format:

new_list = [expression for member in iterable]

which method is more efficient

OK, now that we've learned how to use loops, map(), and list comprehensions to create lists, the question "Which is more efficient" may be in your mind. Let's analyze it!

import random
import timeit
VAT_PERCENT = 0.1
PRICES = [random.randrange(100) for x in range(100000)]
def add_vat(price):
    return price + (price * VAT_PERCENT)
    
def get_grand_prices_with_map():
    return list(map(add_vat, PRICES))
    
def get_grand_prices_with_comprehension():
    return [add_vat(price) for price in PRICES]
Python学习交流Q群:660193417###
def get_grand_prices_with_loop():
    grand_prices = []
    for price in PRICES:
        grand_prices.append(add_vat(price))
    return grand_prices
print(timeit.timeit(get_grand_prices_with_map, number=100))
print(timeit.timeit(add_grand_prices_with_comprehension, number=100))
print(timeit.timeit(get_grand_prices_with_loop, number=100))

output:

0.9833468980004909  # with_map
1.197223742999995   # with_comprehension
1.3564663889992516  # with_loop

As we've seen now, the best way to create a list is map() , followed by list comprehensions and loops last.

However, the choice of method should depend on what you want to achieve.

• Use map() to make your code more efficient.

• The use of loops can make the idea of ​​the code show more clearly.

• Using list comprehensions allows you to make your code more compact and efficient. This is the best way to create a list because it is the most readable.
Please add image description

Guess you like

Origin blog.csdn.net/m0_67575344/article/details/124368393