[英]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. 我的第一个想法是使用
map()
,但是这只需要将一个函数应用于序列中的所有项目。
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
. 例如,在以下代码中,我希望将
str.upper()
应用于第一个项目,并将int
应用于每个a
的第二个项目。 " transform
" is a place holder for the effect I'm after. “
transform
”是我追求的效果的占位符。
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.