[Python-ideas] Map to Many Function

Mark Tse mark.tse at neverendingqs.com
Tue Aug 18 01:58:33 CEST 2015


What is the difference between itertools.chain.from_iterable() and
itertools.chain()? I know I had to do itertools.chain(*map(function,
iterable)) before posting to the mailing list.

On Sun, Aug 16, 2015 at 10:16 AM, Akira Li <4kir4.1i at gmail.com> wrote:

> Mark Tse <mark.tse at neverendingqs.com>
> writes:
>
> > 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]
> >
> > Proposal: new built-in method or standard library function to do mapmany.
> >
>
> There is itertools.chain:
>
>   >>> from itertools import chain
>   >>> list(chain.from_iterable(map(lambda x: [x, x], [1, 2, 3, 4])))
>   [1, 1, 2, 2, 3, 3, 4, 4]
>   >>> [item for x in [1, 2, 3, 4] for item in [x, x]]
>   [1, 1, 2, 2, 3, 3, 4, 4]
>
> > Sample use case:
> > Library JSON data returns a list of authors, and each author has a list
> of
> > books:
> >
> > { [ { 'author': 'name', 'books': ['book1', 'book2'] }, { 'author': 'name,
> > 'books': ['book3', 'book4'] }, ... ] }
> >
> > allbooks = list(mapmany(lambda x: x['books'], json))
> >
>
>   allbooks = list(chain.from_iterable(map(itemgetter('books'), json_data)))
>
> Or
>
>   allbooks = [book for x in json_data for book in x['book']]
>
> _______________________________________________
> 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/20150817/8320b4f6/attachment.html>


More information about the Python-ideas mailing list