Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

flatMap or bind in Python 3?

Python provides list comprehensions that provide map/filter type functionality. Can I do a flatMap aka bind operation with this? I've seen solutions with itertools or other add-on libraries. Can I do this with core Python?

# this
[[x,10*x] for x in [1,2,3]]
# will result in unflattened [[1, 10], [2, 20], [3, 30]]
like image 681
user2684301 Avatar asked Jan 28 '14 22:01

user2684301


2 Answers

[y for x in [1, 2, 3] for y in [x, 10*x]]

Just add another for to the list comprehension.

like image 176
user2357112 supports Monica Avatar answered Nov 20 '22 08:11

user2357112 supports Monica


See python list comprehensions; compressing a list of lists?.

from functools import reduce
def flatMap(array: List[List]): List
    return reduce(list.__add__, array)
    # or return reduce(lambda a,b: a+b, array)
like image 1
JP Zhang Avatar answered Nov 20 '22 06:11

JP Zhang