[python篇] [伯乐在线][1]永远别写for循环

首先,让我们退一步看看在写一个for循环背后的直觉是什么:

1.遍历一个序列提取出一些信息

2.从当前的序列中生成另外的序列

3.写for循环已经是我的第二天性了,因为我是一个程序员

幸运的是,Python里面已经有很棒的工具帮你达到这些目标!你需要做的只是转变思想,用不同的角度看问题。

不到处写for循环你将会获得什么

1.更少的代码行数

2.更好的代码阅读性

3.只将缩进用于管理代码文本

Let’s see the code skeleton below:

看看下面这段代码的构架:

Python

# 1
with ...:
    for ...:
        if ...:
            try:
            except:
        else:
1
2
3
4
5
6
7
# 1
with ...:
    for ...:
        if ...:
            try:
            except:
        else:
这个例子使用了多层嵌套的代码,这是非常难以阅读的。我在这段代码中发现它无差别使用缩进把管理逻辑(with, try-except)和业务逻辑(for, if)混在一起。如果你遵守只对管理逻辑使用缩进的规范,那么核心业务逻辑应该立刻脱离出来。

“扁平结构比嵌套结构更好” – 《Python之禅》
为了避免for循环,你可以使用这些工具

1. 列表解析/生成器表达式

看一个简单的例子,这个例子主要是根据一个已经存在的序列编译一个新序列:

Python

result = []
for item in item_list:
    new_item = do_something_with(item)
    result.append(item)
1
2
3
4
result = []
for item in item_list:
    new_item = do_something_with(item)
    result.append(item)
如果你喜欢MapReduce,那你可以使用map,或者Python的列表解析:

Python

result = [do_something_with(item) for item in item_list]
1
result = [do_something_with(item) for item in item_list]
同样的,如果你只是想要获取一个迭代器,你可以使用语法几乎相通的生成器表达式。(你怎么能不爱上Python的一致性?)

Python

result = (do_something_with(item) for item in item_list)
1
result = (do_something_with(item) for item in item_list)
2. 函数

站在更高阶、更函数化的变成方式考虑一下,如果你想映射一个序列到另一个序列,直接调用map函数。(也可用列表解析来替代。)

Python

doubled_list = map(lambda x: x * 2, old_list)
1
doubled_list = map(lambda x: x * 2, old_list)
如果你想使一个序列减少到一个元素,使用reduce

Python

from functools import reduce
summation = reduce(lambda x, y: x + y, numbers)
1
2
from functools import reduce
summation = reduce(lambda x, y: x + y, numbers)
另外,Python中大量的内嵌功能可/会(我不知道这是好事还是坏事,你选一个,不加这个句子有点难懂)消耗迭代器:

Python

>>> 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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
>>> 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. 抽取函数或者表达式

上面的两种方法很好地处理了较为简单的逻辑,那更复杂的逻辑怎么办呢?作为一个程序员,我们会把困难的事情抽象成函数,这种方式也可以用在这里。如果你写下了这种代码:

Python

results = []
for item in item_list:
    # setups
    # condition
    # processing
    # calculation
    results.append(result)
1
2
3
4
5
6
7
results = []
for item in item_list:
    # setups
    # condition
    # processing
    # calculation
    results.append(result)
显然你赋予了一段代码太多的责任。为了改进,我建议你这样做:

Python

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

results = [process_item(item) for item in item_list]
1
2
3
4
5
6
7
8
def process_item(item):
    # setups
    # condition
    # processing
    # calculation
    return result

results = [process_item(item) for item in item_list]
嵌套的for循环怎么样?

Python

results = []
for i in range(10):
    for j in range(i):
        results.append((i, j))
1
2
3
4
results = []
for i in range(10):
    for j in range(i):
        results.append((i, j))
列表解析可以帮助你:

Python

results = [(i, j)
           for i in range(10)
           for j in range(i)]
1
2
3
results = [(i, j)
           for i in range(10)
           for j in range(i)]
如果你要保存很多的内部状态怎么办呢?

Python

# 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]
1
2
3
4
5
6
7
8
9
# 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]
让我们提取一个表达式来实现这些:

Python

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))
1
2
3
4
5
6
7
8
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))
“等等,你刚刚在那个函数的表达式中使用了一个for循环,这是欺骗!”
好吧,自作聪明的家伙,试试下面的这个。

4. 你自己不要写for循环,itertools会为你代劳

这个模块真是妙。我相信这个模块能覆盖80%你想写下for循环的时候。例如,上一个例子可以这样改写:

Python

from itertools import accumulate
a = [3, 4, 6, 2, 1, 9, 0, 7, 5, 8]
resutls = list(accumulate(a, max))
1
2
3
from itertools import accumulate
a = [3, 4, 6, 2, 1, 9, 0, 7, 5, 8]
resutls = list(accumulate(a, max))
另外,如果你在迭代组合的序列,还有product(),permutations(),combinations()可以用。

结论

1.大多数情况下是不需要写for循环的。

2.应该避免使用for循环,这样会使得代码有更好的阅读性。

行动

首先,让我们退一步看看在写一个for循环背后的直觉是什么:

1.遍历一个序列提取出一些信息

2.从当前的序列中生成另外的序列

3.写for循环已经是我的第二天性了,因为我是一个程序员

幸运的是,Python里面已经有很棒的工具帮你达到这些目标!你需要做的只是转变思想,用不同的角度看问题。

不到处写for循环你将会获得什么

1.更少的代码行数

2.更好的代码阅读性

3.只将缩进用于管理代码文本

Let’s see the code skeleton below:

看看下面这段代码的构架:

Python

1

2

3

4

5

6

7

# 1

with...:

for...:

if...:

try:

except:

else:

这个例子使用了多层嵌套的代码,这是非常难以阅读的。我在这段代码中发现它无差别使用缩进把管理逻辑(with, try-except)和业务逻辑(for, if)混在一起。如果你遵守只对管理逻辑使用缩进的规范,那么核心业务逻辑应该立刻脱离出来。

“扁平结构比嵌套结构更好” – 《Python之禅》

为了避免for循环,你可以使用这些工具

1. 列表解析/生成器表达式

看一个简单的例子,这个例子主要是根据一个已经存在的序列编译一个新序列:

Python

1

2

3

4

result=[]

foritem initem_list:

new_item=do_something_with(item)

result.append(item)

如果你喜欢MapReduce,那你可以使用map,或者Python的列表解析:

Python

1

result=[do_something_with(item)foritem initem_list]

同样的,如果你只是想要获取一个迭代器,你可以使用语法几乎相通的生成器表达式。(你怎么能不爱上Python的一致性?)

Python

1

result=(do_something_with(item)foritem initem_list)

2. 函数

站在更高阶、更函数化的变成方式考虑一下,如果你想映射一个序列到另一个序列,直接调用map函数。(也可用列表解析来替代。)

Python

1

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

如果你想使一个序列减少到一个元素,使用reduce

Python

1

2

fromfunctoolsimportreduce

summation=reduce(lambdax,y:x+y,numbers)

另外,Python中大量的内嵌功能可/会(我不知道这是好事还是坏事,你选一个,不加这个句子有点难懂)消耗迭代器:

Python

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

>>>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. 抽取函数或者表达式

上面的两种方法很好地处理了较为简单的逻辑,那更复杂的逻辑怎么办呢?作为一个程序员,我们会把困难的事情抽象成函数,这种方式也可以用在这里。如果你写下了这种代码:

Python

1

2

3

4

5

6

7

results=[]

foritem initem_list:

# setups

# condition

# processing

# calculation

results.append(result)

显然你赋予了一段代码太多的责任。为了改进,我建议你这样做:

Python

1

2

3

4

5

6

7

8

defprocess_item(item):

# setups

# condition

# processing

# calculation

returnresult

results=[process_item(item)foritem initem_list]

嵌套的for循环怎么样?

Python

1

2

3

4

results=[]

foriinrange(10):

forjinrange(i):

results.append((i,j))

列表解析可以帮助你:

Python

1

2

3

results=[(i,j)

foriinrange(10)

forjinrange(i)]

如果你要保存很多的内部状态怎么办呢?

Python

1

2

3

4

5

6

7

8

9

# finding the max prior to the current item

a=[3,4,6,2,1,9,0,7,5,8]

results=[]

current_max=0

foriina:

current_max=max(i,current_max)

results.append(current_max)

# results = [3, 4, 6, 6, 6, 9, 9, 9, 9, 9]

让我们提取一个表达式来实现这些:

Python

1

2

3

4

5

6

7

8

defmax_generator(numbers):

current_max=0

foriinnumbers:

current_max=max(i,current_max)

yieldcurrent_max

a=[3,4,6,2,1,9,0,7,5,8]

results=list(max_generator(a))

“等等,你刚刚在那个函数的表达式中使用了一个for循环,这是欺骗!”

好吧,自作聪明的家伙,试试下面的这个。

4. 你自己不要写for循环,itertools会为你代劳

这个模块真是妙。我相信这个模块能覆盖80%你想写下for循环的时候。例如,上一个例子可以这样改写:

Python

1

2

3

fromitertoolsimportaccumulate

a=[3,4,6,2,1,9,0,7,5,8]

resutls=list(accumulate(a,max))

另外,如果你在迭代组合的序列,还有product(),permutations(),combinations()可以用。

结论

1.大多数情况下是不需要写for循环的。

2.应该避免使用for循环,这样会使得代码有更好的阅读性。

行动

时间: 2024-08-25 18:17:30

[python篇] [伯乐在线][1]永远别写for循环的相关文章

python抓取伯乐在线的所有文章,对标题分词后存入mongodb中

依赖包: 1.pymongo 2.jieba # -*- coding: utf-8 -*- """ @author: jiangfuqiang """ from HTMLParser import HTMLParser import urllib2 import sys import pymongo import time import jieba import traceback default_encoding = 'utf-8' if s

Python爬虫-爬取伯乐在线美女邮箱

爬取伯乐在线美女邮箱 1.登录界面的进入,设置url,cookie,data,headers 2.进入主页,点击邮箱链接,需要重新设置url,cookie(读取重新保存的cookie),data,headers 1 ''' 2 爬取伯乐在线的美女联系方式 3 需要: 4 1. 登录 5 2. 在登录和相应声望值的前提下,提取对方的邮箱 6 ''' 7 8 from urllib import request, error, parse 9 from http import cookiejar 1

《码农周刊》干货精选--Python篇(转)

原文:http://baoz.me/446252 码农周刊 如何让 Python 代码运行得更快? 作者给出了 18 条 Python 代码性能优化小贴士,简单明了,拿来即用. http://infiniteloop.in/blog/quick-python-performance-optimization-part-i/ Python 学习资源列表 (kirang89) 海量 Python 学习资源列表,涉及 Python 学习的方方面面. https://github.com/kirang8

Scrapy分布式爬虫打造搜索引擎- (二)伯乐在线爬取所有文章

二.伯乐在线爬取所有文章 1. 初始化文件目录 基础环境 python 3.6.5 JetBrains PyCharm 2018.1 mysql+navicat 为了便于日后的部署:我们开发使用了虚拟环境. 1234567891011 pip install virtualenvpip install virtualenvwrapper-win安装虚拟环境管理mkvirtualenv articlespider3创建虚拟环境workon articlespider3直接进入虚拟环境deactiv

Scrapy分布式爬虫打造搜索引擎——(二) scrapy 爬取伯乐在线

1.开发环境准备 1.爬取策略 目标:爬取“伯乐在线”的所有文章 策略选择:由于“伯乐在线”提供了全部文章的索引页 ,所有不需要考虑url的去重方法,直接在索引页开始,一篇文章一篇文章地进行爬取,一直进行到最后一页即可. 索引页地址:http://blog.jobbole.com/all-posts/ 2. 搭建python3虚拟环境 打开cmd,进入命令行,输入workon,查看当前存在的虚拟环境:  workon 为爬虫项目,新建python3虚拟环境: mkvirtualenv -p py

学习编程之Python篇(一)

第一次接触编程,你将面对两大难题: 1.  对所要使用的编程语言的语法和语义不甚了了. 2.  不知道如何通过编程来解决问题. 作为一名新手,你会尝试同时来解决这两个难题:一边熟悉编程语言的语法语义,一边考虑如何靠编程解决问题.这是一个循序渐进的过程,万事开头难,务必保持耐心,切勿操之过急. 学习编程其实没有什么捷径可走,最好的方法就是反复操练,聆听规则,讨论方法,都不如真正做点什么. 在掌握了一些编程语言的语法语义之后,接下来的难题就是怎样才能写出好的程序.那么,我们首先来看看什么是好的程序.

C++混合编程之idlcpp教程Python篇(8)

上一篇在这 C++混合编程之idlcpp教程Python篇(7) 第一篇在这 C++混合编程之idlcpp教程(一) 与前面的工程相似,工程PythonTutorial6中,同样加入了四个文件:PythonTutorial6.cpp, Tutorial6.cpp, Tutorial6.i, tutorial6.py.其中PythonTutorial6.cpp的内容基本和PythonTutorial5.cpp雷同,不再赘述.首先看一下Tutorial6.i的内容: #import "../../p

C++混合编程之idlcpp教程Python篇(4)

上一篇在这 C++混合编程之idlcpp教程Python篇(3) 第一篇在这 C++混合编程之idlcpp教程(一) 与前面的工程相似,工程PythonTutorial2中,同样加入了三个文件 PythonTutorial2.cpp, Tutorial2.i, tutorial2.py.其中PythonTutorial2.cpp的内容基本和PythonTutorial1.cpp雷同,不再赘述.首先看一下Tutorial2.i的内容: namespace tutorial { struct Poi

C++混合编程之idlcpp教程Python篇(3)

上一篇 C++混合编程之idlcpp教程Python篇(2) 是一个 hello world 的例子,仅仅涉及了静态函数的调用.这一篇会有新的内容. 与PythonTutorial0相似,工程PythonTutorial1中,同样加入了三个文件 PythonTutorial1.cpp, Tutorial1.i, tutorial1.py 其中PythonTutorial1.cpp的内容基本和PythonTutorial0.cpp雷同,不再赘述. 首先看一下Tutorial1.i的内容: name