2

I have 3 functions (f1, f2 and f3) that each take an input and return a str.

These functions are stored in a list in an order that is determined by settings in a program prior to receiving inputs. Their ordering may be different each time a program is run:

# User A's run:
funcs = [f1, f1, f2, f1, f3]

# User B's run:
funcs = [f3, f3, f2]

During program execution, a list of inputs will be generated that correspond the to ordering of funcs. That is to say, the item type of each index in the list inputs will be the correct type expected by the function at the corresponding index of funcs:

# f1 expects int
# f2 expects float
# f3 expects str

funcs = [f1, f1, f2, f1, f3]
inputs = [0, 1, 3.14, 10, 'abc']

I need to map funcs to inputs element-wise and concatenate the resulting string. Currently I solve this by using zip:

result = ''.join(f(i) for f, i in zip(func, inputs))

Is there another way to achieve this type of mapping or is zip the ideal way?

  • zip seems to be the most efficient way; you could loop through and do per item in the funcs list, but your implementation is cleaner. – Ironkey Oct 07 '20 at 14:58
  • 1
    The only potentially better way I see is to replace the generator with a list comprehension for efficiency. – superb rain Oct 07 '20 at 15:04
  • `zip` works and is clear. People will disagree on what is "ideal". – btilly Oct 07 '20 at 15:41
  • @superbrain in what way would a list comprehension be more efficient? the generator is obviously memory efficient, but does `join()` perform better with a list comprehension? *Edit*: found [this](https://stackoverflow.com/a/34822788/7811364) post that explains an explicit conversion in the implementation. –  Oct 07 '20 at 15:51
  • @pasta_sauce Also see [this](https://stackoverflow.com/a/9061024/13008439). – superb rain Oct 07 '20 at 17:17

1 Answers1

1

I think you can import FunctionType and map each function to each input directly (tried it with a list of lambdas and it does work):

from types import FunctionType
funcs = [f1,f1,f2,f1,f3]
inputs = [0, 1, 3.14, 10, 'abc']
"".join(map(FunctionType.__call__, funcs, inputs))
DDD1
  • 361
  • 1
  • 11