私は好奇心として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 comprehensionを使用したくないと言います。何百万、何千、何百万?答えが100万の場合、その反復は私の基本的なデスクトップマシンで約0.13秒かかります。あなたの答えが1000万〜10000万であれば、データが必ずしもメモリに保持されているわけではなく、プライマリクエリに迅速に回答できるようにデータが格納されている場所が必要です。 – FMc