I have been experimenting and trying to learn the Numexpr package. Examples on how to use it are sparse at best. Can someone please give me a quick example on how to use the "local_dict" and "global_dict" arguments?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
The following examples may clarify it a little. First set up the scene like this:
import numpy as np
import numexpr as ne
a = np.arange(10)
b = np.arange(10, 20)
c = np.arange(20, 30)
No dict
>>> def f0(a, b) :
... a, b = 2 * a, 3 * b
... return ne.evaluate('2*a + 3*b + c')
...
>>> f0(a, b)
array([110, 124, 138, 152, 166, 180, 194, 208, 222, 236])
>>> 4 * a + 9 * b + c
array([110, 124, 138, 152, 166, 180, 194, 208, 222, 236])
When you run it like this, a
and b
are the local variables, and c
is the global variable, as expected.
local_dict
>>> def f1(a, b) :
... a, b = 2 * a, 3 * b
... return ne.evaluate('2*a + 3*b + c',
... local_dict={'c' : np.arange(30, 40)})
...
>>> f1(a, b)
array([ 60, 66, 72, 78, 84, 90, 96, 102, 108, 114])
>>> 2*a + 3 * b + np.arange(30, 40)
array([ 60, 66, 72, 78, 84, 90, 96, 102, 108, 114])
Because we have redefined local_dict
, a
and b
no longer show up there as local variables, so the value of the global ones is used instead. And because c
now is defined as a local variable, the value of the global one is ignored.
global_dict
>>> def f2(a, b) :
... a, b = 2 * a, 3 * b
... return ne.evaluate('2*a + 3*b + c',
... global_dict= {'c' : np.arange(30, 40)})
...
>>> f2(a, b)
array([120, 134, 148, 162, 176, 190, 204, 218, 232, 246])
>>> 4 * a + 9 * b + np.arange(30, 40)
array([120, 134, 148, 162, 176, 190, 204, 218, 232, 246])
In this case, a
and b
are taken from the default local dictionary, and the new c
is taken in place of the original global one.