地图返回列表代替lis的实现

2024-05-15 00:30:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试实现我自己版本的Python的map函数。我把它叫做我的地图。约束条件是使用函数式编程(如果允许语句,则不允许循环)

以下是实现方法:

# f is the function it takes in, and ls is the list to apply this function over.
def my_map(f, ls):
    if len(ls) != 1:
        ret = my_map(f, ls[1:])
        return [f(ls[0])] + [ret]
    else:
        return f(ls[0])

但是当我用以下输入运行它时:

def f(x):
    return x * x

my_map(f, [1,2,3,4])返回[1, [4, [9, 16]]]

map(f, [1,2,3,4])返回[1, 4, 9, 16],这正是我所期望的

你知道我怎样才能得到预期的结果吗


Tags: the函数版本mapreturnismydef
1条回答
网友
1楼 · 发布于 2024-05-15 00:30:15
return [f(ls[0])] + [ret]

应该是

return [f(ls[0])] + ret

是的。您正在从ret创建一个新的单元素列表,但只有第一个列表应该是单元素列表

而且,发电机可能会更有效率。你列了很多单子

def my_map(f, ls):
    it = iter(ls)

    def go():
        yield f(next(it))
        yield from go()

    return list(go())

相关问题 更多 >

    热门问题