Question

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?

Was it helpful?

Solution

What about...:

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

OTHER TIPS

>>> s="pid,5 user,8 program,28 dev,10 sent,9 received,15".split()
>>> [ ( m.upper(),int(n)) for m, n in [i.split(",") for i in s ] ]
[('PID', 5), ('USER', 8), ('PROGRAM', 28), ('DEV', 10), ('SENT', 9), ('RECEIVED', 15)]

I'm currently using this:

def transform(unaries, iterable):
    return map(lambda a, b: a(b), unaries, iterable)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top