gpt4 book ai didi

python - 在 python 中对 map 使用递归

转载 作者:太空狗 更新时间:2023-10-29 22:09:07 25 4
gpt4 key购买 nike

我正在尝试学习函数式编程概念。练习,使用 map/reduce 展平嵌套列表。我的代码。

lists = [ 1 , 2 , [ 3 , 4, 5], 6, [7, 8, 9] ]
def flatten(lists):
return map(lambda x: flatten(x) if isinstance(x,list) else x, lists)

print flatten(lists)

我得到的输出与输入相同。我做错了什么 ?递归如何与 map() 一起工作?

最佳答案

这是一个同时使用 mapreduce 的解决方案:

def flatten(seq):
return reduce(operator.add, map(
lambda x: flatten(x) if isinstance(x,list) else [x],
seq))

正如 Martijn 所说,map 产生的项目数量与其输入接收的项目数量相同,因此外部步骤需要是 reduce 调用,它为所有输入产生一个输出。 map 可以在这里使用,而不是使所有输入一致:即一系列列表。

关于python - 在 python 中对 map 使用递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33888314/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com