如何使用递归将函数应用于列表

时间:2015-10-02 18:28:06

标签: python

如何使用递归将类似square(x)的函数应用于[1,2,3]这样的列表?我想在不使用内置map函数的情况下得到结果[1,4,9]。 我写了这样的东西,但这会导致错误,永远不会结束。我怎么能改变这个?

lst=[1,2,3]

def f(x):                                                                          

    return x**2

def map(lst,f):

    i=0
    if i>len(lst):
        return 0
    else:
        lst[i]=f(lst[i])
        i+=1
        return map(lst,f)

1 个答案:

答案 0 :(得分:0)

这有效:

def f(x):
    return x ** 2

def recursive_map(values, f):
    if not values:
        return []
    else:
        # Here we concatenate the f(head) + tail together:
        return [f(values[0])] + recursive_map(values[1:], f)

values = [1, 2, 3, 4, 5]
result = recursive_map(values, f)
print(result)
  

[1, 4, 9, 16, 25]

不确定这是否有助于您理解如何编写递归函数。请记住,您始终以“end”子句开头,在这种情况下,当输入为空时返回空列表[]