Home > Backend Development > Python Tutorial > Three options | Abandon the for loop and make Python code more pythonic!

Three options | Abandon the for loop and make Python code more pythonic!

WBOY
Release: 2023-04-12 20:46:04
forward
1452 people have browsed it

Three options | Abandon the for loop and make Python code more pythonic!

Why should you challenge yourself not to write a for loop in your code? Because this forces you to learn to use more advanced and more idiomatic syntax or libraries. The article uses python as an example to talk about a lot of syntax that everyone has seen in other people's code but rarely uses it themselves.

It’s been a while since I started exploring the amazing language features in Python. In the beginning, I gave myself a challenge with the goal of allowing me to practice more Python language features than I would have had programming experience with other programming languages. This makes things more and more interesting! The code becomes more and more concise, and the code looks more structured and standardized. I will describe these benefits below.

The for loop is usually used in the following usage scenarios:

  • To extract some information in a sequence.
  • Generate one sequence from another.
  • Writing for has become a habit.

Luckily, Python already has a lot of tools to help you do this, you just need to shift your mind and think about it from a different perspective.

What benefits do you get by avoiding writing for loops:

  • Less amount of code
  • Better code readability
  • Less indentation (still makes sense for Python)

Let’s take a look at the following code structure:

# 1
with ...:
 for ...:
 if ...:
 try:
 except:
 else:
Copy after login

In this example, we are dealing with multiple levels Nested code, which is difficult to read. This example uses multiple levels of nested code. What I found in this code was the indiscriminate use of indentation to mix management logic (with, try-except) and business logic (for, if). If you adhere to the convention of only using indentation for administrative logic, then the core business logic should be taken out immediately.

"Flat structures are better than nested structures" - The Zen of Python

You can use existing tools to replace for loops

1.List Comprehension / Generator Expression

Let’s look at a simple example. If you want to convert one array to another:

result = []
for item in item_list:
 new_item = do_something_with(item)
 result.append(item)
Copy after login

If you like MapReduce, you can also use map, or List Comprehension in Python:

result = [do_something_with(item) for item in item_list]
Copy after login

Similarly, if you just want To iterate over the elements in an array, you can also use the same code Generator Expression. result = (do_something_with(item) for item in item_list)

2. Function

If you want to map one array to another array, just call the map function, and you can use an updated Advanced, more practical programming approaches solve this problem.

doubled_list = map(lambda x: x * 2, old_list)
Copy after login

If you want to reduce a sequence to a single one, use reduce

In addition, many Python built-in functions use iterables:

>>> a = list(range(10))
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> all(a)
False
>>> any(a)
True
>>> max(a)
9
>>> min(a)
0
>>> list(filter(bool, a))
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> set(a)
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
>>> dict(zip(a,a))
{0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9}
>>> sorted(a, reverse=True)
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
>>> str(a)
'[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]'
>>> sum(a)
45
Copy after login

3.Extract Functions or Generators

The above two methods are good for handling simpler logic. How about more complex logic? As programmers, we write functions to abstract away complex business. The same idea applies here. If you write like this:

results = []
for item in item_list:
 # setups
 # condition
 # processing
 # calculation
 results.append(result)
Copy after login

Obviously you are adding too much responsibility to a block of code. Instead, I suggest you do:

def process_item(item):
 # setups
 # condition
 # processing
 # calculation
 return result
results = [process_item(item) for item in item_list]
Copy after login

What happens if you change to a nested function:

results = []
for i in range(10):
 for j in range(i):
 results.append((i, j))
Copy after login

Change to List Comprehension to achieve this:

results = [(i, j)
for i in range(10)
for j in range(i)]
Copy after login

If your The code block needs to record some internal state:

# finding the max prior to the current item
a = [3, 4, 6, 2, 1, 9, 0, 7, 5, 8]
results = []
current_max = 0
for i in a:
 current_max = max(i, current_max)
 results.append(current_max)
# results = [3, 4, 6, 6, 6, 9, 9, 9, 9, 9]
Copy after login

We use generator to achieve this:

def max_generator(numbers):
 current_max = 0
 for i in numbers:
 current_max = max(i, current_max)
 yield current_max
a = [3, 4, 6, 2, 1, 9, 0, 7, 5, 8]
results = list(max_generator(a))
Copy after login

Readers may ask "Wait a minute! You used a for loop in the generator, cheating!" Don't worry, take a look at the code below.

Don't write it yourself. itertools will help you implement it

This module is very simple. I believe this module can replace your original one in most scenarios The for loop. For example, the last example can be rewritten as:

from itertools import accumulate
a = [3, 4, 6, 2, 1, 9, 0, 7, 5, 8]
resutls = list(accumulate(a, max))
Copy after login

Also, if you want to iterate over the combination sequence, you need to use product(), permutations(), combinations().

Conclusion

  • In most cases, you do not need to write a for loop.
  • You should avoid writing for loops, which will result in better code readability.

The above is the detailed content of Three options | Abandon the for loop and make Python code more pythonic!. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:51cto.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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template