python循环输入一个数组,的Python:在附加功能到一个数组FOR循环

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)...])

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.

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)]).

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)]

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)

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值