如何写出优雅的Python(二)

 

Print sorted list:

colors=['red','green','blue','yellow']

for color in sorted(colors):
    print color

for color in sorted(colors,reverse=True):
    print color

 

Customer sort order:

Bad:

colors=['red','green','blue','yellow']

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)

 

Good:

colors=['red','green','blue','yellow']

print sorted(colors,cmp=len)

 

Call a function until a sentinel value:

Bad:

blocks=[]
while True:
    block = f.read(32)
    if block == '':
        break
    blocks.append(block)

 

Good:

blocks=[]
for blocks in iter(partial(f.read,32), ''):
    blocks.append(block)
posted @ 2015-07-24 22:35  db2zos  阅读(236)  评论(0编辑  收藏  举报