Search code examples
pythondictionarytransformpredicateunary-function

Transform items from iterable with a sequence of unary functions


I frequently find myself needing to apply a sequence of unary functions to a sequence of of the same length. My first thought is to go with map(), however this only takes a single function to be applied to all items in the sequence.

In the following code for example, I wish to apply str.upper() to the first item, and int to the second item in each a. "transform" is a place holder for the effect I'm after.

COLS = tuple([transform((str.upper, int), a.split(",")) for a in "pid,5 user,8 program,28 dev,10 sent,9 received,15".split()])

Is there some standard library, or other nice implementation that can perform a transformation such as this neatly?


Solution

  • What about...:

    def transform(functions, arguments):
      return [f(a) for f, a in zip(functions, arguments)]