Home > Article > Backend Development > Challenge: Alternatives to implementing loops in Python
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:
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:
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.
Existing tools that can be used to replace for loops
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)
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
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))
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().
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!