更新时间:2022-10-25 12:05:25
我认为这应该符合您的功能性"标准,为了回答您的问题,我认为没有一种干净的方法,您应该适应列表理解.
正如@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]