从这个answer窃取表单import timeit
from operator import itemgetter
from itertools import imap
x = range(100)
y = reversed(range(100))
d = [dict((('x',xx), ('y', yy))) for (xx, yy) in zip(x,y)]
# d is [{'y': 99, 'x': 0}, {'y': 98, 'x': 1}, ... ]
D={x:y for x,y in zip(range(10),reversed(range(10)))}
def test_list_comp(d):
return [dd['x'] for dd in d]
def test_list_comp_v2(d):
return [(x["x"], x["y"]) for x in d]
def testD_keys_values(d):
return d.keys()
def test_map(d):
return map(itemgetter('x'), d)
def test_positional(d):
return [dd.values()[1] for dd in d]
def test_lambda(d):
return list(imap(lambda x: x['x'], d))
def test_imap_iter(d):
return list(imap(itemgetter('x'), d))
for test in sorted(globals()):
if test.startswith("test_"):
print "%30s : %s" % (test, timeit.Timer("f(d)",
"from __main__ import %s as f, d" % test).timeit())
for test in sorted(globals()):
if test.startswith("testD_"):
print "%30s : %s" % (test, timeit.Timer("f(D)",
"from __main__ import %s as f, D" % test).timeit())
得出以下结果:
^{pr2}$
显然,最大的成功是使数据的格式更接近您已经需要的格式,但您可能无法控制这一点。在
就名字而言,我称之为转变。在