[python篇] [伯乐在线][1]永远别写for循环
首先,让我们退一步看看在写一个for循环背后的直觉是什么: 1.遍历一个序列提取出一些信息 2.从当前的序列中生成另外的序列 3.写for循环已经是我的第二天性了,因为我是一个程序员 幸运的是,Python里面已经有很棒的工具帮你达到这些目标!你需要做的只是转变思想,用不同的角度看问题。 不到处写for循环你将会获得什么 1.更少的代码行数 2.更好的代码阅读性 3.只将缩进用于管理代码文本 Let’s see the code skeleton below: 看看下面这段代码的构架: Python #
with ...:
for ...:
if ...:
try:
except:
else:
1
2
3
4
5
6
7
#
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循环,这样会使得代码有更好的阅读性。
行动
[python篇] [伯乐在线][1]永远别写for循环的更多相关文章
- 我常用的 Python 调试工具 - 博客 - 伯乐在线
.ckrating_highly_rated {background-color:#FFFFCC !important;} .ckrating_poorly_rated {opacity:0.6;fi ...
- python爬虫scrapy框架——爬取伯乐在线网站文章
一.前言 1. scrapy依赖包: 二.创建工程 1. 创建scrapy工程: scrapy staratproject ArticleSpider 2. 开始(创建)新的爬虫: cd Artic ...
- python爬虫实战(七)--------伯乐在线文章(模版)
相关代码已经修改调试成功----2017-4-21 一.说明 1.目标网址:伯乐在线 2.实现:如图字段的爬取 3.数据:存放在百度网盘,有需要的可以拿取 链接:http://pan.baidu.co ...
- Scrapy爬取伯乐在线的所有文章
本篇文章将从搭建虚拟环境开始,爬取伯乐在线上的所有文章的数据. 搭建虚拟环境之前需要配置环境变量,该环境变量的变量值为虚拟环境的存放目录 1. 配置环境变量 2.创建虚拟环境 用mkvirtualen ...
- 《码农周刊》干货精选(Python 篇)
<码农周刊>已经累计发送了 38 期,我们将干货内容进行了精选.此为 Python 篇. <码农周刊>往期回顾:http://weekly.manong.io/issues/ ...
- 爬虫实战——Scrapy爬取伯乐在线所有文章
Scrapy简单介绍及爬取伯乐在线所有文章 一.简说安装相关环境及依赖包 1.安装Python(2或3都行,我这里用的是3) 2.虚拟环境搭建: 依赖包:virtualenv,virtualenvwr ...
- 《码农周刊》干货精选--Python篇(转)
原文:http://baoz.me/446252 码农周刊,本人有修改 Python标准库,第三方库 按功能进行了分类,之前有一Pythoner说there is a library for ev ...
- Scrapy分布式爬虫打造搜索引擎- (二)伯乐在线爬取所有文章
二.伯乐在线爬取所有文章 1. 初始化文件目录 基础环境 python 3.6.5 JetBrains PyCharm 2018.1 mysql+navicat 为了便于日后的部署:我们开发使用了虚拟 ...
- GitHub 上适合新手的开源项目(Python 篇)
作者:HelloGitHub-卤蛋 随着 Python 语言的流行,越来越多的人加入到了 Python 的大家庭中.为什么这么多人学 Python ?我要喊出那句话了:"人生苦短,我用 Py ...
随机推荐
- Android(java)学习笔记112:Activity中的onCreate()方法分析
1.onCreate( )方法是android应用程序中最常见的方法之一: 翻译过来就是说,onCreate()函数是在activity初始化的时候调用的,通常情况下,我们需要在onCreate()中 ...
- processing制作动态山水背景
效果代码 float theta, step; int num=5, frames = 1200; Layer[] layers = new Layer[num]; // void setup() { ...
- java基础—注解annotation
一.认识注解 注解(Annotation)很重要,未来的开发模式都是基于注解的,JPA是基于注解的,Spring2.5以上都是基于注解的,Hibernate3.x以后也是基于注解的,现在的Struts ...
- java基础—java读取properties文件
一.java读取properties文件总结 在java项目中,操作properties文件是经常要做的,因为很多的配置信息都会写在properties文件中,这里主要是总结使用getResource ...
- css实现页面文字不换行、自动换行、强制换行
强制不换行 div{ white-space:nowrap; } 自动换行 div{ word-wrap: break-word; word-break: normal; } 强制英文单词断行 div ...
- C#数组删除元素
一.C#数组删除元素 在C#中,只能在动态数组ArrayList类中对数组执行删除元素的操作.因为动态数组是一个可以改变数组长度和元素个数的数据类型. 示例: using System;using S ...
- VueJS坎坷之路111---_self.$scopedSlots.default is not a function
VueJs + Element 话不多说,直接贴错: _self.$scopedSlots.default is not a function <el-table stripe border r ...
- GoogleTest 之路2-Googletest 入门(Primer)
Why googletest? 为啥要用GoogleTest呢? googletest 是由测试技术Team 开发的带有google 特殊的需求和限制的测试框架. 不管你在什么平台上写C++代码,go ...
- Python基础——异常
捕捉所有异常 for i in range(10): try: input_number=input('write a number') if input_number=='q': break res ...
- django知识分支_1
django知识分支 1.Cookie工作流程: 浏览器向服务器发出请求,服务器接收到浏览器的请求进行处理,服务器设置一个cookie发送给浏览器,浏览器将cookie保存,当需要再次登录的时候,浏览 ...