在python中使用map的递归 [英] Using recursion with map in python
本文介绍了在python中使用map的递归的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
练习,使用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()一起使用?
解决方案
这是一个使用
和 reduce
:
def flatten seq):
return reduce(operator.add,map(
lambda x:flatten(x)if isinstance(x,list)else [x],
seq))
如Martijn所说,地图产生与输入相同数量的项目,所以外部步骤需要成为为所有输入产生单个输出的 reduce
调用。可以在这里使用 map
来使所有输入保持一致:即一系列列表。
I am trying to learn functional programming concepts.
An exercise, Flatten a nested list using map/reduce.
My code.
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)
I get output same as input. What did i do wrong ?
How recursion works with map() ?
解决方案 Here's a solution that uses both map
and reduce
:
def flatten(seq):
return reduce(operator.add, map(
lambda x: flatten(x) if isinstance(x,list) else [x],
seq))
As Martijn said, map produces the same number of items out as it receives on its input, so the outer step needs to be the reduce
call that produces a single output for all of the inputs. map
can be used here instead to make all of the input consistent: i.e. a sequence of lists.
这篇关于在python中使用map的递归的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文