gpt4 book ai didi

python - 为什么 IPython 的 timeit 不能与集合文字一起使用?

转载 作者:太空宇宙 更新时间:2023-11-03 15:11:32 25 4
gpt4 key购买 nike

IPython timeit 在使用设置文字时有时会被破坏:

In [1]: timeit 'potato' in {'spam', 'eggs', 'potato'}
10000000 loops, best of 3: 27.6 ns per loop

In [2]: timeit 'potato' in {'potato'}
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-2-9f61653b85de> in <module>()
----> 1 get_ipython().magic(u"timeit 'potato' in {'potato'}")

/usr/local/lib/python2.7/dist-packages/IPython/core/interactiveshell.pyc in magic(self, arg_s)
2203 magic_name, _, magic_arg_s = arg_s.partition(' ')
2204 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
-> 2205 return self.run_line_magic(magic_name, magic_arg_s)
2206
2207 #-------------------------------------------------------------------------

/usr/local/lib/python2.7/dist-packages/IPython/core/interactiveshell.pyc in run_line_magic(self, magic_name, line)
2124 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
2125 with self.builtin_trap:
-> 2126 result = fn(*args,**kwargs)
2127 return result
2128

/usr/local/lib/python2.7/dist-packages/IPython/core/magics/execution.pyc in timeit(self, line, cell)

/usr/local/lib/python2.7/dist-packages/IPython/core/magic.pyc in <lambda>(f, *a, **k)
191 # but it's overkill for just that one bit of state.
192 def magic_deco(arg):
--> 193 call = lambda f, *a, **k: f(*a, **k)
194
195 if callable(arg):

/usr/local/lib/python2.7/dist-packages/IPython/core/magics/execution.pyc in timeit(self, line, cell)
1011 number = 1
1012 for _ in range(1, 10):
-> 1013 if timer.timeit(number) >= 0.2:
1014 break
1015 number *= 10

/usr/lib/python2.7/timeit.pyc in timeit(self, number)
193 gc.disable()
194 try:
--> 195 timing = self.inner(it, self.timer)
196 finally:
197 if gcold:

<magic-timeit> in inner(_it, _timer)

NameError: global name 'potato' is not defined

IPython v2.2.0,在 python 2.x 和 python3 上均失败。

最佳答案

这是一个bug in IPython ,由 ipython 魔法中扩展 {var} 引用的语法与 python 开发人员为集合文字选择的相同语法冲突引起。

如果遇到此问题,可能的解决方法是使用双花括号转义集合文字:

In [1]: timeit 0 in {0}
# TypeError: argument of type 'int' is not iterable

In [2]: timeit 0 in {{0}}
10000000 loops, best of 3: 60.1 ns per loop

关于python - 为什么 IPython 的 timeit 不能与集合文字一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25992510/

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