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

2024-10-01 17:42:08 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有list with elementscontent = ['121\n', '12\n', '2\n', '322\n'],list with functionsfnl = [str.strip, int]。在

所以我需要将fnl中的每个函数依次应用于content中的每个元素。 我可以通过几个调用来完成这个任务map。在

另一种方式:

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

我只是想知道有没有一种更像Python的方式来做这件事。在

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


Tags: 函数元素mapwith方式contentlistint
2条回答

您可以在此处使用列表理解中的^{} function

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

演示:

^{pr2}$

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

在Python3中,reduce()被移到^{} module;为了向前兼容,您可以从Python2.6以后的模块中导入它:

from functools import reduce

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

注意,对于int()函数,数字周围是否有额外的空白并不重要;int('121\n')不需要剥离新行。在

您正在描述列表理解的基本用法:

>>> content = ['121\n', '12\n', '2\n', '322\n']
>>> [int(n) for n in content]
[121, 12, 2, 322]

注意,这里不需要调用strip来转换为整数,一些空格可以很好地处理。在

但是,如果您的实际用例更复杂,并且您希望在理解中任意组合许多函数,那么我发现here中的想法非常类似于python:

^{pr2}$

相关问题 更多 >

    热门问题