码迷,mamicode.com
首页 > 编程语言 > 详细

如何写出优雅的Python(二)

时间:2015-07-24 23:51:51      阅读:136      评论:0      收藏:0      [点我收藏+]

标签:

 

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)

如何写出优雅的Python(二)

标签:

原文地址:http://www.cnblogs.com/db2zos/p/4674985.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!