简体   繁体   中英

Python map with function that returns variable number of values

In python 3, I have a function that returns a list of variable size

I would like to run this function over a list and concatenate the results. for example::

def the_func(x):
    return [x]*x

def mapvar(f,v):
    ans=[]
    for x in v:
        ans.extend(f(x))
    return ans

print (mapvar(the_func,range(10)))

Is there a best practice in python to do this? if is there a standard mapvar function?

What you've got looks good. I would just factor out flatten and use the builtin map .

def the_func(x):
    return [x] * x

def flatten(lst):
    return [x
        for subl in lst
            for x in subl]

print(flatten(map(the_func, range(10))))

Since the question is tagged [python-3.x], here is a one-liner using map for projection and itertools.chain.from_iterable for flattening:

import itertools
result = list(itertools.chain.from_iterable(map(the_func, range(10))))
print(result)

This is about 1 second faster than the nested for list comprehension version (3.3 seconds vs. 4.1 second) on average using 1 mil. iterations.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM