— 改编自 Python: Tips, Tricks and Idioms
1. Dict的for循环中避免使用低效的iteritems() 和 keys()
a = {}
for i in xrange(0, 1000000):
a[i] = i
print(type(a))
print(len(a))
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
import timeit
print(timeit.timeit(for_func1, number=100))
print(timeit.timeit(for_func2, number=100))
print(timeit.timeit(for_func3, number=100))
是不是快多了?
2. for循环中获得index神器: enumerate
students = ('James', 'Andrew', 'Mark')
for i, student in enumerate(students):
print i, student
students = {'James': 'male', 'Andrew':'male', 'Alice':'female'}
for i, student in enumerate(students):
print i, student
3. 想确定for循环完整结束, 用else吧…
for ele in ['a', 'b', 'c']:
if ele == 'b':
break
else: # no break
print('for循环完整结束')
for ele in ['a', 'b', 'c']:
if ele == 'd':
break
else: # no break
print('for循环完整结束')