[Python-ideas] Map to Many Function

Petr Viktorin encukou at gmail.com
Sat Aug 15 21:34:58 CEST 2015


On Sat, Aug 15, 2015 at 9:18 PM, Mark Tse <mark.tse at neverendingqs.com> wrote:
> Currently, when the function for map() returns a list, the resulting object
> is an iterable of lists:
>
>>>> list(map(lambda x: [x, x], [1, 2, 3, 4]))
> [[1, 1], [2, 2], [3, 3], [4, 4]]
>
> However, a function to convert each element to multiple elements, similar to
> flatMap (Java) or SelectMany (C#) does not exist, for doing the following:
>
>>>> list(mapmany(lambda x: [x, x], [1, 2, 3, 4]))
> [1, 1, 2, 2, 3, 3, 4, 4]

There's no built-in to do it, but with a little help from itertools,
you can get the effect:

>>> import itertools
>>> list(itertools.chain.from_iterable(map(lambda x: [x, x], [1, 2, 3, 4])))
[1, 1, 2, 2, 3, 3, 4, 4]

Wrapping this up in a "mapmany" function should take about two lines of code.


More information about the Python-ideas mailing list