不容错过的Python小贴士—技巧, 风格和最佳实践

— 改编自 Python: Tips, Tricks and Idioms

 

1. Dict的for循环中避免使用低效的iteritems() 和 keys()

In [1]:
a = {}
for i in xrange(0, 1000000):
    a[i] = i
print(type(a))
print(len(a))
<type 'dict'>
1000000
In [2]:
def for_func1():
    for x in a:
        pass

def for_func2():
    for x in a.keys():
        pass

def for_func3():
    for x,v in a.iteritems():
        pass
In [3]:
import timeit
print(timeit.timeit(for_func1, number=100))
print(timeit.timeit(for_func2, number=100))
print(timeit.timeit(for_func3, number=100))
1.22459793091
2.30621099472
2.17837190628

是不是快多了?

 

2. for循环中获得index神器: enumerate

In [4]:
students = ('James', 'Andrew', 'Mark')
In [5]:
for i, student in enumerate(students):
    print i, student
0 James
1 Andrew
2 Mark
In [6]:
students = {'James': 'male', 'Andrew':'male', 'Alice':'female'}
In [7]:
for i, student in enumerate(students):
    print i, student
0 James
1 Andrew
2 Alice

3. 想确定for循环完整结束, 用else吧…

In [8]:
for ele in ['a', 'b', 'c']:
    if ele == 'b':
        break
else: # no break
    print('for循环完整结束')
In [9]:
for ele in ['a', 'b', 'c']:
    if ele == 'd':
        break
else: # no break
    print('for循环完整结束')
for循环完整结束

4. 迭代工具之chain连接器

继续阅读不容错过的Python小贴士—技巧, 风格和最佳实践