gpt4 book ai didi

python - 为什么涉及 list.index() 调用的 lambda 如此慢?

转载 作者:行者123 更新时间:2023-11-30 23:18:33 27 4
gpt4 key购买 nike

使用cProfile:

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
1 0.000 0.000 17.834 17.834 <string>:1(<module>)
1 0.007 0.007 17.834 17.834 basher.py:5551(_refresh)
1 0.000 0.000 10.522 10.522 basher.py:1826(RefreshUI)
4 0.024 0.006 10.517 2.629 basher.py:961(PopulateItems)
211 1.494 0.007 7.488 0.035 basher.py:1849(PopulateItem)
231 0.074 0.000 6.734 0.029 {method 'sort' of 'list' objects}
215 0.002 0.000 6.688 0.031 bosh.py:4764(getOrdered)
1910 3.039 0.002 6.648 0.003 bosh.py:4770(<lambda>)
253 0.178 0.001 5.600 0.022 bosh.py:3325(getStatus)
1 0.000 0.000 5.508 5.508 bosh.py:4327(refresh)
1911 3.051 0.002 3.330 0.002 {method 'index' of 'list' objects}

1910 3.039 0.002 6.648 0.003 bosh.py:4770(<lambda>)线让我困惑。在 bosh.py:4770 我有 modNames.sort(key=lambda a: (a in data) and data.index(a)) 、data 和 modNames 是列表。通知1911 3.051 0.002 3.330 0.002 {method 'index' of 'list' objects}这似乎来自这条线。

那么为什么这么慢呢?无论如何我可以重写这个sort()所以它执行得更快?

编辑:我错过了理解这个 lambda 的最后一个要素:

>>> True and 3
3

最佳答案

正如 YardGlassOfCode 所说,这不是 lambda本身很慢,是 lambda 内部的 O(n) 操作很慢。两者a in datadata.index(a) O(n) operations ,其中n的长度是data 。作为对效率的额外侮辱,调用 index重复 a in data 中完成的大部分工作也。如果 data 中的项目是可散列的,那么您可以通过首先准备一个字典来大大加快速度:

weight = dict(zip(data, range(len(data))))
modNames.sort(key=weight.get) # Python2, or
modNames.sort(key=lambda a: weight.get(a, -1)) # works in Python3

这要快得多,因为 each dict lookup is a O(1) operation .

请注意modNames.sort(key=weight.get)依赖 None 比较小于整数:

In [39]: None < 0
Out[39]: True

在Python3中,None < 0提出 TypeError 。所以lambda a: weight.get(a, -1)用于当 a 时返回 -1不在 weight 中.

关于python - 为什么涉及 list.index() 调用的 lambda 如此慢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26644111/

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