Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/304.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在字符串/数组中存储多个函数值(Python)_Python_String_Function - Fatal编程技术网

在字符串/数组中存储多个函数值(Python)

在字符串/数组中存储多个函数值(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(

我试图在一个数组中存储多个函数值,以便在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

使用列表理解:

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]