且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Python:将函数列表应用于列表中的每个元素

更新时间:2022-02-21 22:41:47

您可以使用

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.