数组中的python存储功能 [英] python store function in array

查看:72
本文介绍了数组中的python存储功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

也许是N00b问题。

我对python很陌生,但是我想知道是否可以在数组中存储函数?我想做一个数组乘法,其中一个数组的值与另一个函数数组位置上的一个函数相乘。或者实际上,第一个数组的值将插入到指定位置的函数中。这应该创建一个新数组,其中的值是乘法的结果。

I am new-ish to python, but I was wondering if it is possible to store a function in an array? I want to do an array multiplication, where the value of one array is multiplied by a function on a location of another array of functions. Or actually, the value of the first array is inserted in the function of the designated location. This should create a new array where the values are an outcome of the "multiplication".

>>> import numpy as np
>>> a = [[1, 0], [0, 1]]
>>> b = [[f(x), g(x)], [(h(x), f(x)]]
>>> np.dot(a, b)
array([[0, 1],
   [2, 0]])

假设f(x),g(x)和h(x)是已定义的函数。在这种情况下,python将说未定义x。到目前为止,我知道。但是,我不想说,例如,f( a [0] [1]),因为我想重用数组b,并且还能够将函数放在数组中的随机位置上。

Assuming that f(x), g(x) and h(x) are defined functions. In this case python will say that x is not defined. So far I know. However, I do not want to say, for example, f(a[0][1]), because I want to reuse array b and also be able to put the functions on random locations in the array.

总之,我检测到三个问题:

-是否有一种已知的方法来将值作为函数的数组?

-如果不是,我应该重新定义数组函数还是编写一个新类为此吗(我该如何解决这个问题?)

-如果可以创建一个函数数组,我可以在数组中动态填充函数值(动态填充数组)吗?函数)还是只能是静态值?

In short I detect three questions:
- Is there a known way to have an array where the values are functions?
- If not, should I redefine an array function or write a new class for this? (how do I attack this problem?)
- If it is possible to create an array of functions, can I fill the 'function values' dynamically in the array (populate the array dynamically with functions) or can it only be static values?

例如

b[0]=f(x)

是,我真的很想使用python。

And yes, I really want to do this with python.

推荐答案

f(x)不是函数(即使在数学中)。函数是f。在python中,将函数存储在数组中没有问题:

f(x) is not a function (even in mathematics). The function is f. In python there is no problem to store functions in array:

def my_func():
    print("Foo")

my_other_func = lambda: print("Bar")

my_arr = [my_func, my_other_func]

这篇关于数组中的python存储功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆