Transforming Code into Beautiful,Idiomatic Python(1)

原文位置:http://sssslide.com/speakerdeck.com/pyconslides/transforming-code-into-beautiful-idiomatic-python-by-raymond-hettinger-1

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)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值