用Python创建字典列表的最有效方法
假设我有一个对象列表,我想为每个对象创建一个字典,并将我生成的所有字典放在一个列表中 我现在做的是:用Python创建字典列表的最有效方法,python,list,dictionary,Python,List,Dictionary,假设我有一个对象列表,我想为每个对象创建一个字典,并将我生成的所有字典放在一个列表中 我现在做的是: def f(x): some function f that returns a dictionary given x list_of_dict = [] xlist = [x1, x2, ..., xN] for x in xlist: list_of_dict.append(f(x)) 我想知道是否有比我提议的更有效(更快)的方法来创建字典列表 谢谢。因为您处理的是H
def f(x):
some function f that returns a dictionary given x
list_of_dict = []
xlist = [x1, x2, ..., xN]
for x in xlist:
list_of_dict.append(f(x))
我想知道是否有比我提议的更有效(更快)的方法来创建字典列表
谢谢。因为您处理的是HTTP请求(这在您的问题中并不明显),所以答案的其余部分无关紧要:通信将以绝对优势主导计算。无论如何,我将把答案留在这里
最初的方法似乎是最慢的:
In [20]: %%timeit
...: list_of_dict = []
...: for x in xlist:
...: list_of_dict.append(f(x))
...:
13.5 µs ± 39.3 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
映射是最好的方法:
In [21]: %timeit list(map(f,xlist))
8.45 µs ± 17 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
列表理解处于中间位置:
In [22]: %timeit [f(x) for x in xlist]
10.2 µs ± 22.8 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
输入速度更快,还是执行速度更快?你安排好你的活动时间了吗?感觉上花了很长时间吗?有多少项?执行速度更快。xlist包含大约2000000个元素,除了提高函数f的效率外,我还想知道是否可以加快列表的创建速度。
append
循环可以替换为list\u of dict=[f(x)for x in xlist]
,但您必须对它进行计时,看看它是否更快。如果不了解f(x)
的作用,我们就无法合理地推荐任何东西。如果你得到很多重复,也许会缓存结果。谢谢。xlist是一个链接列表,函数f使用beautifulSoup从链接请求并解析html页面,创建两个字符串列表,然后将它们压缩为一个字典。map
通常是将函数应用于列表中每个元素的更快方法之一。所以您可以这样做:list\u of_dict=map(f(x)表示xlist中的x)