2016-11-21 213 views
-4

我必須執行以下操作:評估函數在Python

A function eval_f(f, xs) which takes a function f = f(x) and a list xs of values that should be used as arguments for f. The function eval_f should apply the function f subsequently to every value x in xs, and return a list fs of function values. I.e. for an input argument xs=[x0, x1, x2,..., xn] the function eval_f(f, xs) should return [f(x0), f(x1), f(x2), ..., f(xn)].

import math 


def eval_f(f, xs): 

    x = [] 
    f = f(x) 
    for i in range(len(xs)): 
     f.append(f(x[i])) 
    return f 

eval_f(math.sqrt,[1,2,4,9]) 回溯(最近最後調用):

文件 「」,第1行,在 eval_f(math.sqrt,[1,2,4,9])

文件 「C:/Users/Idoia/untitled2.py」,第6行,在eval_f f = f(x)

類型錯誤:需要一個浮動

+3

而且?怎麼了? –

+2

你的問題是什麼? –

+0

它顯示一個錯誤,說它需要一個浮點數 –

回答

0
def test(x): 
    return x*2 

def eval_f(f, xs): 
    ans = [] 
    for x in xs: 
     ans.append(f(x)) 
    return ans 

print(eval_f(test,[1,2,3,4,5])) 

打印出:

[2, 4, 6, 8, 10] 
+0

謝謝你是完美的! –

+0

我明白,這可能是他們想要一個詳細的解決方案的某種作業,但在Python中,你可以簡單地執行'map(f,list)'來替換循環。 – pie3636

+0

的確如此。更多「Pythonic」 – abacles

1

for an input argument xs=[x0, x1, x2,..., xn] the function eval_f(f, xs) should return [f(x0), f(x1), f(x2), ..., f(xn)].

你想map功能f在列表

如果使用Python3,

def eval_f(f, xs): 
    return list(map(f, xs)) 

您可以移除list() for python2