Using recursion with a map in python

I am trying to learn the concepts of functional programming. An exercise. Flatten the nested list using the 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 the output the same as the input. What have I done wrong? How does recursion work with map ()?

+4
source share
4 answers

Here's a solution that uses both mapand reduce:

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

, , , reduce, . map , : .. .

+7

map(). , . map() , , .

reduce() :

def flatten(lists):
    return reduce(lambda res, x: res + (flatten(x) if isinstance(x, list) else [x]), lists, [])

lists. , .

:

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

map , , .

map reduce, , :

>>> def flatten(lists):
...     for sub in lists:
...         if isinstance(sub,list):
...            for i in sub:
...                 yield i
...         else:
...            yield sub
... 
>>> 
>>> list(flatten(lists))
[1, 2, 3, 4, 5, 6, 7, 8, 9]

map, :

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

:

lists = [ 1 , 2 , [ 3 , 4, 5], 6, [7, 8, 9] ]
def flatten(lists):
    return (flatten(lists[0]) + flatten(lists[1:]) if isinstance(lists[0],list) else [lists[0]]+flatten(lists[1:])) if len(lists)>0 else []
0

Source: https://habr.com/ru/post/1617192/


All Articles