在 Python 中的对象上应用函数列表 [英] Apply list of functions on an object in Python
问题描述
有没有干净的方法可以在没有 lambda 或列表推导式的情况下在 Python 中的对象上应用函数列表?就像 Haskell 表达式一样:
map ($obj) [foo1,foo2]
Python 中的 lambda 示例:
response = map(lambda foo:foo(obj),[foo1,foo2]) #fooX:object->Bool
是否可以扩展到类函数?
也许是运算符或 itertools 的东西?
我认为这应该符合您的功能性"标准,为了回答您的问题,我认为没有一种干净的方法,您应该适应列表理解.
正如@J.F.Sebastian 所建议的
<预><代码>>>>从操作符导入方法调用者>>>funcs = (lambda x: x + 1, lambda x: x + 2)>>>目标 = 5>>>列表(地图(方法调用者('__call__',obj),函数))[6, 7]这是一种疯狂的做法:
<预><代码>>>>从 itertools 导入星图,重复>>>从类型导入 FunctionType>>>funcs = (lambda x: x + 1, lambda x: x + 2)>>>目标 = 5>>>列表(星图(FunctionType.__call__,zip(funcs,repeat(obj))))[6, 7]正如@AleksiTorhamo 所建议的
<预><代码>>>>从 itertools 导入重复>>>从类型导入 FunctionType>>>目标 = 5>>>funcs = (lambda x: x + 1, lambda x: x + 2)>>>列表(地图(FunctionType.__call__,funcs,repeat(obj)))[6, 7]Is there any clean way to apply a list of functions on an object in Python without lambda or list comprehensions? Like the Haskell expression:
map ($ obj) [foo1,foo2]
Example with lambda in Python:
response = map(lambda foo:foo(obj),[foo1,foo2]) #fooX:object->Bool
Is it extendable to class functions?
Perhaps something from operator or itertools?
I think this should fit your 'functional' criteria, To answer your question, I don't think there is a clean way and you should just acclimatize to list comprehensions.
As suggested by @J.F.Sebastian
>>> from operator import methodcaller
>>> funcs = (lambda x: x + 1, lambda x: x + 2)
>>> obj = 5
>>> list(map(methodcaller('__call__', obj), funcs))
[6, 7]
Here is a crazy way of doing it:
>>> from itertools import starmap, repeat
>>> from types import FunctionType
>>> funcs = (lambda x: x + 1, lambda x: x + 2)
>>> obj = 5
>>> list(starmap(FunctionType.__call__, zip(funcs, repeat(obj))))
[6, 7]
As suggested by @AleksiTorhamo
>>> from itertools import repeat
>>> from types import FunctionType
>>> obj = 5
>>> funcs = (lambda x: x + 1, lambda x: x + 2)
>>> list(map(FunctionType.__call__, funcs, repeat(obj)))
[6, 7]
这篇关于在 Python 中的对象上应用函数列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!