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?
xrangeis a sequence object that evaluates lazily.xrangecreates 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支持开发的高级重用机制,例 ...
随机推荐
- HPUX 只取syslog.log当前三天的信息
LOG_DAYS=1todays_date=`date +%m:%d:%Y`current_date=`echo $todays_date | sed 's/://g'`day=`echo $toda ...
- 初识Android NDK
本文介绍Windows环境下搭建Android NDK开发环境,并创建一个简单的使用Native代码的Android Application. 一.环境搭建 二.JNI函数绑定 三.例子 一.环境搭建 ...
- 3D旋转相册(适合新手)
<!DOCTYPE HTML> <html onselectstart="return false"> <head> <meta char ...
- Direct3D学习笔记 - 浅析HDR Lighting Sample
一.HDR简介 HDR(High Dynamic Range,高动态范围)是一种图像后处理技术,是一种表达超过了显示器所能表现的亮度范围的图像映射技术.高动态范围技术能够很好地再现现实生活中丰富的亮度 ...
- Ping of Death
[Ping of Death] The ping of death attack, or PoD, can cripple a network based on a flaw in the TCP/I ...
- [python] Ubuntu 环境下安装 python3.5 + pip
一般情况下先添加PPA,但是我添加PPA会报错: sudo add-apt-repository ppa:fkrull/deadsnakes ubuntu add-apt-repository: co ...
- MySQL 5.7版本sql_mode=only_full_group_by问题
用到GROUP BY 语句查询时com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Expression #2 of SELECT l ...
- Maven Archetype
1. 从project创建archetype 在项目根目录下,运行 mvn archetype:create-from-project 创建的archetype工程在app_folder/target ...
- 【活动】监控宝惹火Docker监控,开放试用中
要说这两年最火爆的技术有哪些,Docker绝对是其中之一. 有人说,Docker缺少必要的运维监控工具,实践起来有难度. 幸福来的太快了. 云智慧旗下产品监控宝又惹火了,推出重量级新功能——Docke ...
- [转载] Android随笔之——PackageManager详解
本文转载自: http://www.cnblogs.com/travellife/p/3932823.html 参考:http://www.cnblogs.com/xingfuzzhd/p/33745 ...