標籤:
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 izipnames = [‘raymond‘,‘rachel‘,‘mattew‘]colors = [‘red‘,‘green‘,‘blue‘,‘yellow‘]for name,color in izip(names,colors): print name,‘-->‘,color
如何寫出優雅的Python