— 改编自 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))
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))
是不是快多了?
2. for循环中获得index神器: enumerate
In [4]:
students = ('James', 'Andrew', 'Mark')
In [5]:
for i, student in enumerate(students):
print i, student
In [6]:
students = {'James': 'male', 'Andrew':'male', 'Alice':'female'}
In [7]:
for i, student in enumerate(students):
print i, student
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循环完整结束')