惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

博客园_首页
C
Check Point Blog
B
Blog RSS Feed
G
Google Developers Blog
H
Help Net Security
博客园 - Franky
Blog — PlanetScale
Blog — PlanetScale
H
Hackread – Cybersecurity News, Data Breaches, AI and More
量子位
Recent Announcements
Recent Announcements
B
Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
D
DataBreaches.Net
小众软件
小众软件
T
The Blog of Author Tim Ferriss
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
MongoDB | Blog
MongoDB | Blog
Y
Y Combinator Blog
T
Tailwind CSS Blog
J
Java Code Geeks
MyScale Blog
MyScale Blog
雷峰网
雷峰网
有赞技术团队
有赞技术团队
博客园 - 聂微东

博客园 - db2zos

从假后端到 Cloudflare D1:一次医疗旅游网站的重构实践 没想到老外在中国还可以开车呀 用 API 获取官方统计数据,原来可以这么简单 放弃ipup系列,开始使用更先进的nmcli来管理你的网络 定期启动vpn - db2zos 几段Python小程序 关于职业的一点忧虑和思考 select in 在postgresql的效率问题 Ansible 学习笔记 ldap配置记录 nis,nfs,pam小结 docker命令小记 性能调优利器之strace 如何写出优雅的Python(二) [LeeCode]Power of Two 分布式数据库架构一例 如何写出优雅的Python之设置class缺省值 Mac 使用笔记 开启刷题模式 从简单需求到OLAP的RANK系列函数 数据库的Index Scan V.S. Rscan
如何写出优雅的Python
db2zos · 2015-07-19 · via 博客园 - db2zos

Looping over a range of numbers

Bad:

for i in [0,1,2,3,4,5]:
    print i**2

Good:

for i in range(6):
    print i**2

Looping over a collection:

Bad:

colors = [ 'red','green','blue','yellow']

for i in range(len(colors)):
    print colors[i]

Good:

for i in colors:
    print colors[i]

Looping backwards

Bad:

colors = ['red','green','blue','yellow']

for i in range(len(colors)-1,-1,-1):
    print colors(i)

Good:

colors = ['red','green','blue','yellow']

for color in reversed(colors):
    print color

Looping over a collection and indicies

Bad:

colors = ['red','green','blue','yellow']

for i in range(len(colors)):
    print i, '-->', colors[i]

 Good:

colors = ['red','green','blue','yellow']

for i,color in enmerate(colors):
    print i, '-->', colors[i]

Looping over two collections

Bad:

names = ['raymond','rachel','mattew']
colors = ['red','green','blue','yellow']

n = min(len(names),len(colors))
for i in range(n):
    print names[i],'-->',colors[i]

Good:

names = ['raymond','rachel','mattew']
colors = ['red','green','blue','yellow']

for name,color in zip(names,colors):
    print name,'-->',color

Even beeter.(izip 依次处理,zip是全部读入后处理,如果在中间中断的话,izip不需要读入所有内容)

from itertools import izip
names = ['raymond','rachel','mattew']
colors = ['red','green','blue','yellow']

for name,color in izip(names,colors):
    print name,'-->',color