[Python-ideas] Map to Many Function

MRAB python at mrabarnett.plus.com
Tue Aug 18 02:30:23 CEST 2015


On 2015-08-18 00:58, Mark Tse wrote:
> 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.
>
itertools.chain() expects the iterables as individual arguments,
whereas itertools.chain.from_iterable() expects the iterables to be
provided by a single argument that will yield those iterables itself;
that means that you don't have to unpack them first as you're doing.

> On Sun, Aug 16, 2015 at 10:16 AM, Akira Li <4kir4.1i at gmail.com
> <mailto:4kir4.1i at gmail.com>> wrote:
>
>     Mark Tse <mark.tse at neverendingqs.com
>     <mailto: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']]
>



More information about the Python-ideas mailing list