当前位置:主页 > 资料 >

Idiomatic Python: Loops
栏目分类:资料   发布日期:2017-05-28   浏览次数:

导读:本文为去找网小编(www.7zhao.net)为您推荐的Idiomatic Python: Loops,希望对您有所帮助,谢谢! ##Use xrange instead of tranditional index manipulation # NOT SO GOODfor i in [0, 1, 2, 3, 4, 5]: print i * 2#BETTERfor i i

本文为去找网小编(www.7zhao.net)为您推荐的Idiomatic Python: Loops,希望对您有所帮助,谢谢!

去找(www.7zhao.net欢迎您



##Use xrange instead of tranditional index manipulation 去找(www.7zhao.net欢迎您

# NOT SO GOOD
for i in [0, 1, 2, 3, 4, 5]:
    print i * 2

#BETTER
for i in range(6):
    print i*2

#BEST
for i in xrange(6):
    print i*2
 
www.7zhao.net

##Use reverse to loop backwards 欢迎访问www.7zhao.net

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

#NOT SO GOOD
for i in range(len(colors)-1, -1, -1):
    print colors[i]

#GOOD
for color in reversed(colors):
    print color
 www.7zhao.net 

##Use enumerate to loop over a collection and indices#2. List

本文来自去找www.7zhao.net

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

#NOT SO GOOD
for i in range(len(colors)):
    print i, " -> ", colors[i]
    
#GOOD
for i, color in enumerate(colors):
    print i, " -> ", colors[i]
 
www.7zhao.net

##Use izip to loop over two collections

欢迎访问www.7zhao.net

colors = ['red', 'green', 'blue', 'yellow']
names = ['Archie', 'Ben', 'Chris', 'Dave']

#NOT SO GOOD
n = min(len(colors), len(names))
for i in range(n):
    print colors[i], ' -> ', names[i]

#BETTER
for name, color in zip(names, colors):
    print color, ' -> ', name

#BEST
from itertools import izip
for name, color in izip(names, colors):
    print color, ' -> ', name
 
copyright www.7zhao.net

##Use sorted to loop in sorted order www.7zhao.net

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

#NORMAL
for color in sorted(colors):
    print color

#REVERSE
for color in sorted(colors, reversed=True):
    print color


#CUSTOM COMPARATOR
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())
print sorted(colors, key=len)
 

内容来自www.7zhao.net

##Use for…else… to distinguish multiple exit points in loops

去找(www.7zhao.net欢迎您

The “else” here is better explained by “no break”. 去找(www.7zhao.net欢迎您

#NOT SO GOOD
def find(seq, target):
    found = False
    for i, value in enumerate(seq):
        if value == target:
            found = True
            break
    if not found:
        return -1
    return i


#GOOD
def find(seq, target):
    for i, value in enumerate(seq):
        if value == target:
            break
    else:
        return -1
    return i
 www.7zhao.net 
本文来自去找www.7zhao.net


本文原文地址:http://codethink.me/2014/08/09/idiomatic-python-loops/

以上为Idiomatic Python: Loops文章的全部内容,若您也有好的文章,欢迎与我们分享!

内容来自www.7zhao.net

Copyright ©2008-2017去找网版权所有   皖ICP备12002049号-2 皖公网安备 34088102000435号   关于我们|联系我们| 免责声明|友情链接|网站地图|手机版