码迷,mamicode.com
首页 > 编程语言 > 详细

如何写出优雅的Python

时间:2015-07-19 23:30:34      阅读:201      评论:0      收藏:0      [点我收藏+]

标签:

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

 

如何写出优雅的Python

标签:

原文地址:http://www.cnblogs.com/db2zos/p/4660007.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!