Python:将函数列表应用于列表中的每个元素 [英] Python: apply list of functions to each element in list

查看:145
本文介绍了Python:将函数列表应用于列表中的每个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个元素为content = ['121\n', '12\n', '2\n', '322\n']的列表和一个函数为fnl = [str.strip, int]的列表.

Say I have list with elements content = ['121\n', '12\n', '2\n', '322\n'] and list with functions fnl = [str.strip, int].

所以我需要依次将fnl中的每个函数应用于content中的每个元素. 我可以通过几个电话map来做到这一点.

So I need to apply each function from fnl to each element from content sequentially. I can do this by several calls map.

另一种方式:

xl = lambda func, content: map(func, content)
for func in fnl:
    content = xl(func, content) 

我只是想知道是否还有一种更Python化的方式来做到这一点.

I'm just wondering if there is a more pythonic way to do it.

没有单独的功能?用单一表达?

Without separate function? By single expression?

推荐答案

您可以使用

You could use the reduce() function in a list comprehension here:

[reduce(lambda v, f: f(v), fnl, element) for element in content]

演示:

>>> content = ['121\n', '12\n', '2\n', '322\n']
>>> fnl = [str.strip, int]
>>> [reduce(lambda v, f: f(v), fnl, element) for element in content]
[121, 12, 2, 322]

这将每个函数依次应用于每个元素,就像您嵌套了调用一样;转换为int(str.strip(element))fnl = [str.strip, int].

This applies each function in turn to each element, as if you nested the calls; for fnl = [str.strip, int] that translates to int(str.strip(element)).

在Python 3中,reduce()已移至 functools模块;为了向前兼容,您可以从Python 2.6及更高版本的模块中将其导入:

In Python 3, reduce() was moved to the functools module; for forwards compatibility, you can import it from that module from Python 2.6 onwards:

from functools import reduce

results = [reduce(lambda v, f: f(v), fnl, element) for element in content]

请注意,对于int()函数,数字周围是否有多余的空格都无关紧要; int('121\n')可以在不删除换行符的情况下工作.

Note that for the int() function, it doesn't matter if there is extra whitespace around the digits; int('121\n') works without stripping of the newline.

这篇关于Python:将函数列表应用于列表中的每个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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