地址: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.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架