gpt4 book ai didi

python - 什么更有效地迭代列表并调用函数或将列表传递给函数

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:44:34 26 4
gpt4 key购买 nike

我有一个充满字典的列表,我想为每个字典应用一个函数。什么是更有效或最佳实践,以迭代列表并将字典传递给每次迭代的函数。就像这里显示的那样:

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)

或者您可能知道其他方法。如果两种方法都同样有效,你更喜欢哪一种,为什么?

最佳答案

在性能方面,发送整个列表会更快,因为 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)

关于python - 什么更有效地迭代列表并调用函数或将列表传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31824144/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com