[Python-ideas] Map to Many Function
Wes Turner
wes.turner at gmail.com
Sun Aug 16 03:29:02 CEST 2015
On Aug 15, 2015 2:35 PM, "Petr Viktorin" <encukou at gmail.com> wrote:
>
> 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.
I think this is something like toolz.itertoolz.mapcat:
https://toolz.readthedocs.org/en/latest/api.html#toolz.itertoolz.mapcat
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20150815/24ed06a6/attachment.html>
More information about the Python-ideas
mailing list