开发者

How to map a list of data to a list of functions?

开发者 https://www.devze.com 2023-01-18 18:06 出处:网络
I have the following Python code: data= [\'1\', \'4.6\', \'txt\'] funcs = [int, float, str] How to call every开发者_开发技巧 function with data in corresponding index as an argument to the function

I have the following Python code:

data  = ['1', '4.6', 'txt']
funcs = [int, float, str]

How to call every开发者_开发技巧 function with data in corresponding index as an argument to the function? Now I'm using the code:

result = []
for i, func in enumerate(funcs):
    result.append(func(data[i]))

map(funcs, data) don't work with lists of functions ( Is there builtin function to do that simpler?


You could use zip* to combine many sequences together:

zip([a,b,c,...], [x,y,z,...]) == [(a,x), (b,y), (c,z), ...]

then you could iterate on this new sequence and make each function apply on the corresponding data. Since you just want to collect them into a list, list comprehension is much better than a for-loop:

result = [f(x) for f, x in zip(funcs, data)]

Note: * Use itertools.izip if you are using Python 2.x and the lists are very long.)


[f(d) for d,f in zip(data, funcs)]


>>> data  = ['1', '4.6', 'txt']
>>> funcs = [int, float, str]
>>> result = [funcs[pos](x) for pos, x in enumerate(data)]
>>> result
[1, 4.5999999999999996, 'txt']
>>> 


map() will work with sequences of functions, although perhaps not in the way you thought:

data  = ['1', '4.6', 'txt']
funcs = [int, float, str]

result = list(map(lambda f,d: f(d), funcs, data))
# or
result = list(map(lambda d,f: f(d), data, funcs))


If you need the values one by one, you can also create generator for values:

def my_funcvals(funcs,vals):
    return ("%s(%r) = %r" %(f.__name__,d, f(d)) for d,f in zip(data, funcs))

data  = ['1', '4.6', 'txt']
funcs = [int, float, str]

for result in my_funcvals(funcs, data):
    print result
0

精彩评论

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