python代码优化---就喜欢细节
地址:http://www.codeproject.com/Tips/829060/Python-Code-Optimizations-Part-One
转发过来保存一下。喜欢精雕细琢,编程才有乐趣。作者牛。
Introduction
Listed below are some very common day to day usage scenarios, and a way to do them pythonically!
Using the Code
1. Looping over a Range of Numbers
- for i in [0,1,2,3,4,5]:
- print i**2
Better way (looks better):
- for i in range(6):
- print i**2
What Happens in this Loop?
range
produces a list in memory and then the for
loop loops over the list.
Both create a list of 6 integers in memory and then iterate over each
number, raise it to power 2 and then print. Thus, both the loops do
exactly the same thing in exactly the same way!
Pythonic way: Use xrange()
- #Python 2.x
- for i in xrange(6):
- print i**2
- #Python 3.x
- for i in range(6):
- print i**2
What is xrange?
xrange
is a sequence object that evaluates lazily.xrange
creates an iterator over the range(list) and yields one number at a time, thus consuming less amount of memory than the methods above.
2. Looping Over a Collection
- colours = ['red', 'green', 'blue', 'yellow']
- for i in range(len(colours)):
- print colours[i]
Pythonic way
- for colour in colours:
- print colour
3. Looping Over a Collection and its Indices
- for i in range(len(colours)):
- print i, '-->', colours[i]
Pythonic way: use enumerate()
- for i, colour in enumerate(colours):
- print i, '-->', colour
4. Looping Backwards
- for i in range(len(colours), -1, -1, -1):
- print colours[i]
Pythonic way: Use reversed()
- for colour in reversed(colours):
- print colour
5. Loooping in Sorted Order
Pythonic way: Use sorted()
- for colour in sorted(colours):
- print colour
Looping Backwards in Sorted Order
Just add reverse=True
to the sorted function arguments list.
Pythonic Way
- for colour in sorted(colours, reverse=True):
- print colour
6. Looping Over Two Collections
- names = ['a', 'b', 'c']
- colours = ['red', 'green', 'blue', 'yellow']
- n = min(len(colours), len(names))
- for i in range(n):
- print names[i], '-->', colours[i]
Better Way
- for name, colour in zip(names, colours):
- print name, '-->', colour
zip
creates a third list in memory which consists of tuples, each of which is its own separate object with pointers back to the original. In other words, it takes far more memory than the original two lists combined.
Most importantly "It doesn't scale!".
Pythonic Way: use izip()
- from itertools import izip
- for name, colour in izip(names, colours):
- print name, '-->', colour
For smaller lists, zip
is faster, but if you have lists with millions of records, then better use izip
, as izip
only advances the underlying iterators when needed.
python代码优化---就喜欢细节的更多相关文章
- python基础===Python 代码优化常见技巧
Python 代码优化常见技巧 代码优化能够让程序运行更快,它是在不改变程序运行结果的情况下使得程序的运行效率更高,根据 80/20 原则,实现程序的重构.优化.扩展以及文档相关的事情通常需要消耗 8 ...
- Python 代码优化常见技巧
代码优化能够让程序运行更快,它是在不改变程序运行结果的情况下使得程序的运行效率更高,根据 80/20 原则,实现程序的重构.优化.扩展以及文档相关的事情通常需要消耗 80% 的工作量.优化通常包含两方 ...
- python代码优化技巧
转自:http://www.douban.com/group/topic/31478102/ 这个资料库还有些不错的好文章: http://www.ibm.com/developerworks/cn/ ...
- python函数的参数细节
按"指针"传递 python中变量赋值.参数传递都是通过"指针"拷贝的方式进行的.除了按"指针"拷贝,还有一种按值拷贝的方式,关于按值.按指 ...
- Python 代码优化技巧(一)
Table of Contents 1. 代码优化Part1 1.1. if 判断的短路特性 1.2. join 合并字符串 1.3. while 1 和 while True 1.4. cProfi ...
- Python代码优化概要
Python即是面向过程语言,也是面向对象语言,很多其它情况下充当脚本语言的角色.虽是脚本语言,但相同涉及到代码优化的问题,代码优化可以让程序执行更快,它是在不改变程序执行结果的情况下使程序执行效率更 ...
- Python代码优化及技巧笔记(一)
前言 这里是记录一些本人在开发过程中遇到的一些细节问题.与君共勉. 版权说明 著作权归作者全部.商业转载请联系作者获得授权,非商业转载请注明出处. 作者:Coding-Naga链接:http://bl ...
- 提高 python 效率的一些细节方式
在列表里面计数 性能:第二种计数方法比第一种快6290倍,为啥因为Python原生的内置函数都是优化过的,所以能用原生的计算的时候,尽量用原生的函数来计算. 过滤一个列表 性能:第二种方法比第一种慢近 ...
- python为什么人们喜欢学习呢?
软件的质和量. 既有量的积累也有质的区别.继承一定的前人研究基础. 基本上来说,python更加的注重可读性,一致性,可移植性,其中软件的质量也是比较的讲究的. python支持开发的高级重用机制,例 ...
随机推荐
- Nuget版本冲突的问题
有两个类库项目,一个引用了比如Newtonsoft.Json 6.0, 另一个引用了比如Newtonsoft.Json 8.0, 然后另一个exe项目同时引用了这两个类库项目. 那么在编译的时候会报w ...
- js计时事件
通过在一个设定的时间间隔之后来执行代码,而不是在函数被调用后立即执行,我们称之为计时事件. 1. setTimeout()--暂停指定的时间后执行指定的代码 clearTimeout ()--停止se ...
- asp.net前台代码中引入namespace的方法
<%@ import NameSpace="System.Data.OleDb" %>
- 仿东软OA协同办公服务管理系统
兼容IE6,7,8以上.GooleChrome.360及遨游等浏览器.系统特色:1.系统经过抗压测试.2.语音提示功能.3.支持office2007在线编辑.4.强大的图形化工作流程设计及文档编辑留痕 ...
- location对象
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...
- centos 6.5 查看、开启,关闭 端口
查看所有端口 netstat -ntlp 1.开启端口(以80端口为例) 方法一: /sbin/iptables -I INPUT -p tcp --dp ...
- Reflector.exe 破解注意事项
需要把网络断掉,然后选择手动激活 总结经验:操作步骤要仔细看清,否则会更浪费时间
- 通过XmlHttpRequest实现带进度条异步下载文件
本博文源自技术群的讨论,因为网上找不到实现这样效果的的代码,而我说没问题,可以实现,因此有人质疑我是否能做到,呵呵,现将我实现代码贴出如下,希望有兴趣的同学可以继续完善: 本代码仅做技术展现,请勿探讨 ...
- JS中变量名作为if条件的 true/flase
在Javascript中,可以直接将变量名放到if条件中, var a;//甚至不定义 if (a){ //... } 以下情况被认为是flase: 1.''空的字符串 2.数字0 3.对象null ...
- 网页链接qq
<a href="mqqwpa://im/chat?chat_type=wpa&uin=12345678&version=1&src_type=web& ...