Home  >  Article  >  Backend Development  >  Challenge: Alternatives to implementing loops in Python

Challenge: Alternatives to implementing loops in Python

WBOY
WBOYforward
2023-05-07 09:28:071044browse

挑战不再写Python for 循环

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:

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

Existing tools that can be used 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)

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

result = [do_something_with(item) for item in item_list]

Similarly, if you only want to iterate over the

elements in the 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 an array to another array, just call the map function to solve this problem in a more advanced and practical programming way.

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

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

from functools import reduce
summation = reduce(lambda x, y: x + y, numbers)

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

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)

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]

What will happen if you change to a nested function?

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

Change to List Comprehension to achieve something like this:

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

If your code The 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]

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))
  • Readers may ask, "Wait a minute! You used a for loop in the generator, that's cheating. ! Don’t worry, look at the following code again.

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

This module is very simple. I believe this module can be used in most scenarios You can replace your original 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))

In addition, if you want to iterate the combined 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 make the code more readable sex.

The above is the detailed content of Challenge: Alternatives to implementing loops in Python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:51cto.com. If there is any infringement, please contact admin@php.cn delete