开发者

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 fun开发者_如何学运维ction 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?


What about...:

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


>>> 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)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜