的Python:在附加功能到一个数组FOR循环 [英] Python: Add function to an array in a FOR loop
问题描述
也许这是一个简单的问题,但我无法到目前为止找到有关它的任何信息。
对于 numpy的
优化我需要一个函数数组。我需要的功能的数量取决于其应优化当前对象。
我已经想通了如何动态创建这些功能,但现在我想将它们存储在一个这样的数组:
Maybe this is a simple issue, but I could not find any information about it so far.
For an optimization in numpy
I need an array of functions. The number of functions I need depends on the current object which shall be optimized.
I have already figured out how to create these functions dynamically, but now I would like to store them in an array like this:
myArray = zeros(x)
for i in range(x):
myArray[i] = createFunction(i)
如果我运行此我得到一个类型不匹配:
浮动()参数必须是一个字符串或数字,而不是功能
If I run this I get a type mismatch: float() argument must be a string or a number, not 'function'
直接创建数组运行良好:
Creating the array directly works well:
myArray = array([createFunction(0)...])
但是,因为我不知道我需要的功能的数量,这正是我想要prevent。
But because I don't know the number of functions I need, this is exactly what I want to prevent.
推荐答案
嗯,我明白了。你真的意味着的函数数组的。
Ah, I get it. You really do mean an array of functions.
类型不匹配错误的产生是由于在调用零
默认创建彩车的数组。所以,你原来会工作相反,如果你没有 myArray的= numpy.empty(X,DTYPE = numpy.object)
(注意,空
使得比零
这里)更有意义。稍微更Python化版本是使用一个列表的COM prehension
The type mismatch error arises because the call to zeros
creates an array of floats by default. So your original would work if instead you did myArray = numpy.empty(x, dtype=numpy.object)
(note that empty
makes more sense than zeros
here). The slightly more pythonic version is to use a list comprehension
myArray = numpy.array([createFunction(i) for i in range(x)]).
但是,你可能并不需要在所有创建numpy的阵列,这取决于你想用它做什么:
But you might not need to create a numpy array at all, depending on what you want to do with it:
myArray = [createFunction(i) for i in range(x)]
如果你想避免的名单,它可能是最好使用的 numpy.fromfunction
一起的 numpy.vectorize
:
If you want to avoid the list, it might be better to use numpy.fromfunction
along with numpy.vectorize
:
myArray = numpy.fromfunction(numpy.vectorize(createFunction),
shape=(x,), dtype=numpy.object)
其中,(X,)
是一个元组给数组的形状。到矢量
是必须的呼叫,因为 fromfunction
假定该函数可以输入数组上工作并返回数组标量和矢量
转换功能做到这一点。否则numpy的尝试的 DTYPE =对象
需要创建彩车组成的数组。
where (x,)
is a tuple giving the shape of the array. The call to vectorize
is needed because fromfunction
assumes that the function can work on an array of inputs and return an array of scalars, and vectorize
converts a function to do exactly that. The dtype=object
is needed since otherwise numpy tries to create an array of floats.
这篇关于的Python:在附加功能到一个数组FOR循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!