views:

45

answers:

3

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?

+1  A: 
>>> 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)]
ghostdog74
+4  A: 

What about...:

def transform(functions, arguments):
  return [f(a) for f, a in zip(functions, arguments)]
Alex Martelli
actually it does
Matt Joiner
+1  A: 

I'm currently using this:

def transform(unaries, iterable):
    return map(lambda a, b: a(b), unaries, iterable)
Matt Joiner
How does this perform with relation to Alex Martelli's answer, which looks somewhat simpler?
Matt Joiner