python map flatmap - ghdrako/doc_snipets GitHub Wiki

there's no built-in flat_map function

id = lambda x: x
flat_map(id, [1,2], [3,4](/ghdrako/doc_snipets/wiki/1,2],-[3,4)) == [1, 2, 3, 4]

s = lambda x: split(x, ";")
flat_map(s, ["a,b", "c,d"]) == ["a", "b", "c", "d"]

Map reduce

from functools import reduce
flat_map = lambda f, xs: reduce(lambda a, b: a + b, map(f, xs))
>>> from functools import reduce  # not needed on Python 2
>>> list_of_lists = [1, 2],[3, 4, 5], [6](/ghdrako/doc_snipets/wiki/1,-2],[3,-4,-5],-[6)
>>> reduce(list.__add__, list_of_lists)
[1, 2, 3, 4, 5, 6]

Map sum

flat_map = lambda f, xs: sum(map(f, xs), [])

For and extend

def flat_map(f, xs):
    ys = []
    for x in xs:
        ys.extend(f(x))
    return ys

List comprehension - best solution

flat_map = lambda f, xs: [y for ys in xs for y in f(ys)]
[filename for path in dirs for filename in os.listdir(path)]
[ item for list in listoflists for item in list ]

generator

flat_map = lambda f, xs: (y for ys in xs for y in f(ys))

using generator expression is only applicable when we are going to iterate over the result.