假设有一个集合,集合中有大量元素,这些元素可能是字典(dict),也可能是类(class)的实例(instance),然后我们想对这些元素的某个键值或者是某个属性进行加总。传统做法是对集合进行循环,还有一种更高效的方法则是通过列表推导式实现。
# 循环方法
def loop(l):
result = 0
for i in range(0, len(l)):
result += l[i]['b']
return result
# 列表推导式方法
def listComprehension(l):
result = sum([x['b'] for x in l])
return result
In [2]: testList = [{'a':1, 'b':2, 'c':3, 'd':4}]*1000000
In [3]: %timeit loop(testList)
10 loops, best of 3: 70.1 ms per loop
In [4]: %timeit listComprehension(testList)
10 loops, best of 3: 56.9 ms per loop
In [5]: testList = [{'a':1, 'b':2, 'c':3, 'd':4}]*10000000
In [6]: %timeit loop(testList)
1 loop, best of 3: 705 ms per loop
In [7]: %timeit listComprehension(testList)
1 loop, best of 3: 619 ms per loop