我有一个列有字典的列表,对于每个字典,我想要应用一个函数。什么是更有效或最佳实践,迭代列表并将dict传递给每次迭代的函数。如下所示:
dict1 = {"foo": 8, "bar": 4, "baz":2}
dict2 = {"foo": 3, "bar": 6, "baz":3}
...
dict_list = [dict1, dict2, ...]
def function_iterate(dict):
...
for dict in dict_list:
function_iterate(dict)
或者最好传递列表并在函数内迭代:
dict1 = {"foo": 8, "bar": 4, "baz":2}
dict2 = {"foo": 3, "bar": 6, "baz":3}
...
dict_list = [dict1, dict2, ...]
def function_iterate(dict_list):
for dict in dict_list:
...
function_iterate(dict_list)
或许你也知道另一种方法。如果两种方法都有效,你更喜欢哪一种?为什么?
答案 0 :(得分:2)
您可以使用map
:
map(function, dict_list)
map
是一个内置的python函数:https://docs.python.org/2/library/functions.html#map
答案 1 :(得分:1)
性能方面,发送整个列表会更快,因为python中的函数调用很昂贵(性能明智)。
时间测试示例 -
代码 -
l = [{1:2},{2:3},{3:4}]
def func1(d):
for k in d:
d[k] += 1
def func2(l):
for d in l:
for k in d:
d[k] += 1
计时结果 -
In [29]: %%timeit
....: for d in l:
....: func1(d)
....:
The slowest run took 7.57 times longer than the fastest. This could mean that an intermediate result is being cached
1000000 loops, best of 3: 1.16 µs per loop
In [30]: %%timeit
....: func2(l)
....:
The slowest run took 9.25 times longer than the fastest. This could mean that an intermediate result is being cached
1000000 loops, best of 3: 988 ns per loop
In [31]: %%timeit
....: [func1(d) for d in l]
....:
100000 loops, best of 3: 1.98 µs per loop
In [33]: %%timeit
....: list(map(func1,l))
....:
The slowest run took 4.42 times longer than the fastest. This could mean that an intermediate result is being cached
100000 loops, best of 3: 2.5 µs per loop
为了便于阅读,map()
会更好,因为它更具可读性。示例 -
对于Python 3.x -
list(map(function, list_of_dicts))
对于Python 2.x -
map(function, list_of_dicts)