如何写出优雅的Python

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

 

posted @ 2015-07-19 22:28  db2zos  阅读(201)  评论(0编辑  收藏  举报