我试图在数组中存储多个函数值,以便在python中绘制函数。
例如,让我们定义函数是y = x ^ 2,所需的参数值是1,2和3.我尝试的代码如下:
def ExampleFunction (x):
return x**2
ArgumentValues=range(3)
FunctionValues=ExampleFunction(ArgumentValues)
不幸的是,运行代码会导致错误:
TypeError: unsupported operand type(s) for ** or pow(): 'range' and 'int'
如何在python中将许多函数值返回到字符串/数组?结果我想要"函数值"采取以下形式:
1,4,9
答案 0 :(得分:2)
使用列表理解:
results = [ExampleFunction(x) for x in range(3)]
答案 1 :(得分:1)
此代码答案:
def ExampleFunction (x):
list_fn = []
for item in x :
list_fn.append(item**2)
return list_fn
ArgumentValues=range(3)
FunctionValues=ExampleFunction(ArgumentValues)
或者这段代码:
def ExampleFunction (x):
return x**2
ArgumentValues=range(3)
FunctionValues= [ExampleFunction(x) for x in ArgumentValues]
答案 2 :(得分:1)
这是map
的完美用法。
map(lambda x: x**2, range(3))
# [0, 1, 4]
在Python 3.X中,map
将返回map object
而不是列表,因此如果您想重复使用它,则需要将其显式转换为list
。< / p>