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

空扰寡人 提交于 2020-06-22 01:14:45

问题


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?


回答1:


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




回答2:


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




回答3:


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



回答4:


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



回答5:


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


来源:https://stackoverflow.com/questions/3848829/how-to-map-a-list-of-data-to-a-list-of-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!