如何将数据列表映射到函数列表? [英] How to map a list of data to a list of functions?

查看:21
本文介绍了如何将数据列表映射到函数列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下 Python 代码:

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

ma​​p(funcs, data) 不适用于函数列表(是否有内置函数可以更简单地做到这一点?

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

推荐答案

您可以 使用 zip* 将多个序列组合在一起:

You could use zip* to combine many sequences together:

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

然后您可以迭代这个新序列并使每个函数应用于相应的数据.由于您只想将它​​们收集到列表中,列表理解比 for 循环更好:

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

注意:* 使用 itertools.izip 如果您使用的是 Python 2.x 并且列表很长.)

这篇关于如何将数据列表映射到函数列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆