When you see this, do that instead!
- Replace traditional index manipulation with Python’s core looping idioms
- Learn advanced techniques with for-else clauses and two argument form of iter()
- Improve your craftmanship and aim for clean, fast, idiomatic Python code
Looping over a range of numbers
for i in [0,1,2,3,4,5]:
print(i**2)
for i in range(6):
print(i**2)
#for i in xrange(6): #py3没有xrange了。。
# print(i**2)
0
1
4
9
16
25
0
1
4
9
16
25
Looping over a collection
colors=['red','green','blue','yellow']
for i in range(len(colors)):
print(colors[i])
for i in colors:
print(i)
red
green
blue
yellow
red
green
blue
yellow
Looping backwards
#range是的应用!!!
#当start<end时,最后一参数默认为1,可以设定为其它正数
#而当start>end时,最后一参数要为-1,同时也可以设定为其它负数
colors=['red','green','blue','yellow']
for i in range(len(colors)-1,-1,-1):
print(colors[i],end=' ')
yellow blue green red
for i in reversed(colors):
print(i)
yellow
blue
green
red
Looping over a collection and indicies
colors=['red','green','blue','yellow']
for i in range(len(colors)):
print(i+1,'-->', colors[i])
1 --> red
2 --> green
3 --> blue
4 --> yellow
for i,v in enumerate(colors):
print(i+1,'-->',v)
1 --> red
2 --> green
3 --> blue
4 --> yellow
Looping over two collections
names=['raymond','rachel','matthew']
colors=['red','green','blue','yellow']
n=min(len(names),len(colors))
for i in range(n):
print(names[i],'-->',colors[i])
raymond --> red
rachel --> green
matthew --> blue
for name,color in zip(names,colors):
print(name,'-->',color)
raymond --> red
rachel --> green
matthew --> blue
#for name,color in izip(names,colors): izip已经在py3没有了
# print(name,'-->',color)
Looping in sorted order
colors=['red','green','blue','yellow']
for color in sorted(colors):
print(color)
blue
green
red
yellow
for color in sorted(colors,reverse=True):
print(color,end=',')
yellow,red,green,blue,
Custom sort order
colors=['red','green','blue','yellow','hahahah','a']
def compare_length(c1,c2):
if len(c1)<len(c2): return -1
if len(c1)>len(c2): return 1
return 0
#print(sorted(colors,cmp=compare_length)) py3没有这个参数了( sorted(iterable, key=None, reverse=False) )
sorted?
print(sorted(colors,key=len)) #按字长
['a', 'red', 'blue', 'green', 'yellow', 'hahahah']
Call a function until a sentinel value(这个不是很懂,有没有人可以帮我解释一下)
'''
blocks=[]
while True:
block=f.read(32)
if block=='':
break
blocks.append(block)
'''
blocks=[]
for block in iter(partial(f.read,32),''):
blocks.append(block)
&spm=1001.2101.3001.5002&articleId=52605542&d=1&t=3&u=53ab52ecbfdf4d98b01c438b384a2ba6)
809

被折叠的 条评论
为什么被折叠?



