gpt4 book ai didi

python - %timeit 和变量的重新赋值

转载 作者:行者123 更新时间:2023-11-28 22:08:48 28 4
gpt4 key购买 nike

令人惊讶的 ipython 魔法 %timeit 错误:

In[1]: a = 2

In[2]: %timeit a = 2 * a

Traceback (most recent call last):
File "...\site-packages\IPython\core\interactiveshell.py", line 3326, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-97-6f70919654d1>", line 1, in <module>
get_ipython().run_line_magic('timeit', 'a = 2 * a')
File "...\site-packages\IPython\core\interactiveshell.py", line 2314, in run_line_magic
result = fn(*args, **kwargs)
File "<...\site-packages\decorator.py:decorator-gen-61>", line 2, in timeit
File "...\site-packages\IPython\core\magic.py", line 187, in <lambda>
call = lambda f, *a, **k: f(*a, **k)
File "...\site-packages\IPython\core\magics\execution.py", line 1158, in timeit
time_number = timer.timeit(number)
File "...\site-packages\IPython\core\magics\execution.py", line 169, in timeit
timing = self.inner(it, self.timer)
File "<magic-timeit>", line 1, in inner
UnboundLocalError: local variable 'a' referenced before assignment

所以 %timeit 不喜欢 self 重新分配。为什么?无论如何要克服这个?

最佳答案

与底层的 timeit 模块一样,定时语句被集成到执行计时的生成函数中。对 a 的赋值导致函数有一个 a 局部变量,隐藏了全局变量。和你做的一样的问题

a = 2

def f():
a = 2 * a

f()

虽然生成的函数比这有更多的代码。

关于python - %timeit 和变量的重新赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58164023/

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