在字符串/数组中存储多个函数值(Python)
我试图在一个数组中存储多个函数值,以便在python中绘制函数图 例如,让我们定义函数为y=x^2,所需的参数值为1、2和3。我尝试的代码如下所示:在字符串/数组中存储多个函数值(Python),python,string,function,Python,String,Function,我试图在一个数组中存储多个函数值,以便在python中绘制函数图 例如,让我们定义函数为y=x^2,所需的参数值为1、2和3。我尝试的代码如下所示: def ExampleFunction (x): return x**2 ArgumentValues=range(3) FunctionValues=ExampleFunction(ArgumentValues) 很遗憾,运行代码会导致错误: TypeError: unsupported operand type(
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
使用列表理解:
results = [ExampleFunction(x) for x in range(3)]
此代码回答:
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]
这是一个完美的用法
在Python3.X中,
map
将返回一个map对象
,而不是一个列表,因此如果要重用它,需要显式地将其转换为list
函数仍然只返回1个值。
map(lambda x: x**2, range(3))
# [0, 1, 4]