Search code examples
pythonpython-2.7listprocessing-efficiency

Efficiently build a list comprehnsion of numbers and lists


I have a list of functions. Each function may return either a float or a list of 2 floats. I need to build a flat list of results using a list comprhension. For efficiency reasons, I need to build the results using one single iteration. For the same reason, the for loop is not an option (this is my belief... Is this correct?).

Input:

funcs=[[function_1, arguments_function_1],[function_2,arguments_function_2]...[function_n, arguments_function_n]

where function_j is a previously defined function. arguments_function_j is the list of arguments for funtion_j.

Tentative call:

results=[f[0](f[1]) for f in funcs]  

The above call is syntactically correct but does not return the results in the format I need. In facts, assuming that the forth function returns a list, the final result would be

[1,2,3,[4,5],6] instead of  [1,2,3,4,5,6] as I need

I tried the following:

results=[f[0](f[1]) if type(f[0](f[1]))==float\ 
else f[0](f[1])[0],f[0](f[1])[1]\
for f in funcs]  

But the f[0](f[1])[0],f[0](f[1])[1] part is not syntactically correct. It should be placed between bracktes but then it would not solve the problem.

Any hint? Thanks in advance


Solution

  • you just need to chain your values so instead of

    results=[f[0](f[1]) for f in funcs]  
    

    just do

    import itertools
    result = list(itertools.chain.from_iterable(f[0](f[1]) for f in funcs))
    

    (that will flatten your list of results, wrapped in list to force iteration)

    see also: Making a flat list out of list of lists in Python