[Python-ideas] Map to Many Function

Akira Li 4kir4.1i at gmail.com
Sun Aug 16 16:16:29 CEST 2015


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']]



More information about the Python-ideas mailing list