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!

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于Seaborn的相关问题,包括了数据可视化处理的散点图、折线图、条形图等等内容,下面一起来看一下,希望对大家有帮助。

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于进程池与进程锁的相关问题,包括进程池的创建模块,进程池函数等等内容,下面一起来看一下,希望对大家有帮助。

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于简历筛选的相关问题,包括了定义 ReadDoc 类用以读取 word 文件以及定义 search_word 函数用以筛选的相关内容,下面一起来看一下,希望对大家有帮助。

VS Code的确是一款非常热门、有强大用户基础的一款开发工具。本文给大家介绍一下10款高效、好用的插件,能够让原本单薄的VS Code如虎添翼,开发效率顿时提升到一个新的阶段。

pythn的中文意思是巨蟒、蟒蛇。1989年圣诞节期间,Guido van Rossum在家闲的没事干,为了跟朋友庆祝圣诞节,决定发明一种全新的脚本语言。他很喜欢一个肥皂剧叫Monty Python,所以便把这门语言叫做python。

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于数据类型之字符串、数字的相关问题,下面一起来看一下,希望对大家有帮助。

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于numpy模块的相关问题,Numpy是Numerical Python extensions的缩写,字面意思是Python数值计算扩展,下面一起来看一下,希望对大家有帮助。


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Mac version
God-level code editing software (SublimeText3)

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Notepad++7.3.1
Easy-to-use and free code editor

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.
