编辑:我说过听写理解是最快的:我错了。我不小心运行%timeit test3
而不是%timeit test3()
. 请参阅下面的结果。
def test1():
dicta = [{'NAME':'Bob','STATE':'VA','COUNTRY':'US','REGION':'MIDWEST','LNAME':'Brian','Salary':6000}]
remove = ['NAME','STATE','COUNTRY','REGION','LNAME']
for d in dicta:
for r in remove:
d.pop(r)
def test2():
dicta = [{'NAME':'Bob','STATE':'VA','COUNTRY':'US','REGION':'MIDWEST','LNAME':'Brian','Salary':6000}]
remove = ['NAME','STATE','COUNTRY','REGION','LNAME']
for d in dicta:
for r in remove:
del d[r]
def test3():
dicta = [{'NAME':'Bob','STATE':'VA','COUNTRY':'US','REGION':'MIDWEST','LNAME':'Brian','Salary':6000}]
remove = ['NAME','STATE','COUNTRY','REGION','LNAME']
dicta = [{k:v for k,v in d.iteritems() if k not in remove } for d in dicta]
# this is really what OP was looking for, the other 3 tests are more generalized.
def test4():
dicta = [{'NAME':'Bob','STATE':'VA','COUNTRY':'US','REGION':'MIDWEST','LNAME':'Brian','Salary':6000}]
remove = ['NAME','STATE','COUNTRY','REGION','LNAME']
dicta = [e['Salary'] for e in dicta]
%timeit test1()
# 100000 loops, best of 3: 2.32 us per loop
%timeit test2()
# 1000000 loops, best of 3: 1.68 us per loop
%timeit test3()
# 100000 loops, best of 3: 3.23 us per loop
%timeit test4()
# 1000000 loops, best of 3: 1.46 us per loop