gpt4 book ai didi

python 字典/列表理解 : why is it slower than for loop?

转载 作者:太空宇宙 更新时间:2023-11-04 07:36:29 27 4
gpt4 key购买 nike

考虑 events 这里有大约 48,000 个字典对象:

keyed_events = { gid: [ r for r in events if r['gid'] == gid ] for gid in gidlist }

大约比以下慢 4 倍:

keyed_events = {}
for event in events:
gid = event['gid']
if gid not in keyed_events:
keyed_events[gid] = []
keyed_events[gid].append(event)

虽然前者看起来更有效率。为什么比较慢?遍历 events 每次通过字典理解?

最佳答案

keyed_events = { gid: [ r for r in events if r['gid'] == gid ] for gid in gidlist }

列表/字典理解运行 len(gidlist)*len(events) 次,因为它在 gidlist 的循环内循环遍历 events

另一方面,for 循环在 events 上只有一个 for 循环,gid not in keyed_events 这是一个 O(1) 操作

关于python 字典/列表理解 : why is it slower than for loop?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34079231/

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