Home  >  Article  >  Backend Development  >  Detailed explanation of examples of for loops in python

Detailed explanation of examples of for loops in python

零下一度
零下一度Original
2017-07-02 11:07:482225browse

This article mainly introduces some thoughts about the use of for loop in Python. Friends who need it can refer to

Why should we challenge ourselves not to write for in the code? loop? Because this forces you to use more advanced and authentic 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.

This is a challenge. I want you to avoid writing for loops under any circumstances. Similarly, I also want you to find a scenario where it is too difficult to write in any other way except using a for loop. Please share your findings, I'd love to hear about them

It's been a while since I started exploring awesome Python language features. In the beginning, it was just a challenge I gave myself to practice using more language features instead of what I had learned from other programming languages. But things gradually get more interesting! Not only does the code become shorter and cleaner, it also looks more structured and regular, and I'll talk more about these benefits in this article.

First, let’s take a step back and look at the intuition behind writing a for loop:

1. Traverse a sequence to extract some information

2. From the current Generate another sequence from the sequence

3. Writing for loops is second nature to me because I am a programmer

Fortunately, Python already has great Tools to help you achieve these goals! All you need to do is change your mind and see things from a different perspective.

What will you gain by not writing for loops everywhere

1. Fewer lines of code

2. Better code readability

3. Only use indentation to manage code text

Let's see the code skeleton below:

Look at the structure of the following code:


# 1
with ...:
  for ...:
    if ...:
      try:
      except:
    else:

This example uses multiple levels of nested code, which is very difficult to read. 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"

To avoid for loops, you can use these tools

1. List analysis/GeneratorExpression

Look at a simple example. This example mainly compiles a new sequence based on an existing sequence:


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

If you like MapReduce, you can use map, or Python's list parsing:

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

Similarly, if you just want to get an iterator, you can use a generator expression with almost the same syntax. (How could you not fall in love with Python's consistency?)

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

2. Function

Think about it in a higher-order, more functional way. If you want to map one sequence to another, call the map function directly. (List comprehension can also be used instead.)

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

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


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

In addition, a large number of built-in functions in Python can/will (I don’t know if this is a good thing or a bad thing, you choose one, it is a bit not to add this sentence Difficult to understand) Consume iterator:


>>> 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 expressions

The above two methods handle relatively simple logic well , what about more complex logic? As programmers, we abstract difficult things into functions, and this approach can be used here as well. If you write this kind of code:


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

Obviously you are giving too much responsibility to a piece of code. To improve, I suggest you do this:


def process_item(item):
  # setups
  # condition
  # processing
  # calculation
  return result

results = [process_item(item) for item in item_list]

How about nested for loops?


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

List comprehensions can help you:


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

What if you want to save a lot of 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]

Let’s extract an expression to implement these:


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))

“Wait, you just did that A for loop is used in the expression of the function, which is cheating! "

Okay, smart guy, try this.

4. Don’t write the for loop yourself, itertools will do it for you

This module is really wonderful. I believe this module can cover 80% of the times when you want to write a for loop. For example, the previous example can be rewritten like this:


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

In addition, if you are iterating over a sequence of combinations, there are product(), permutations(), and combinations() that can be used .

Conclusion

1. In most cases, there is no need to write a for loop.

2. You should avoid using for loops, which will make the code more readable.

Action

1. Look at your code again and find any place where you have written a for loop intuitively before. Think about it again and write it without a for loop. Again it doesn't make sense.

2. Share an example where it was difficult for you not to use a for loop.

The above is the detailed content of Detailed explanation of examples of for loops in python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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