我已经张贴reduce()
方法的好奇心,但由于答案被接受,我张贴的timeit
结果,比较此票上其他答案的表现。
from timeit import timeit
import functools
def _reduce_py2(the_list):
return reduce(lambda l, src: l.append(src['entry']['Name']) or l, the_list, [])
def _reduce_py3(the_list):
return functools.reduce(lambda l, src: l.append(src['entry']['Name']) or l, the_list, [])
def _map_py2(the_list):
return map(lambda d: d['entry']['Name'], the_list)
def _map_py3(the_list):
return [i for i in map(lambda d: d['entry']['Name'], the_list)]
def _list(the_list):
return [d['entry']['Name'] for d in the_list]
the_list = []
for i in range(1000):
the_list += [{'entry' : {'Name' : 'Smith%s' % i, 'Age' : i}}]
reps = 1000
# Compare timings
print('Reduce: ', timeit('c(the_list)', 'from __main__ import _reduce_py2 as c, the_list', number=reps))
print('Map: ', timeit('c(the_list)', 'from __main__ import _map_py2 as c, the_list', number=reps))
print('List comprehension: ', timeit('c(the_list)', 'from __main__ import _list as c, the_list', number=reps))
结果:
Py 2
Reduce: 0.2090609073638916
Map: 0.136185884475708
List comprehension: 0.07403087615966797
Py 3
Reduce: 0.20160907896934077
Map: 0.17127344600157812
List comprehension: 0.06799810699885711
结论,list comprehension
是最快的方法。不过,python 3上的map
返回了一个生成器。
你说你不想为了性能的原因使用for-loop或list的理解,因为你的数据有“数以百万计”的条目。几百万 - 1,10,100?如果答案是100万,那么我的基本台式机上的迭代大约需要0.13秒。如果你的答案是1000万或1亿,我建议你完全需要一个不同的策略 - 一个是数据不一定保存在内存中,另一个是存储数据的方式,以便你的主要查询可以快速得到回答。 – FMc