在Python中应用函数列表中的对象

在Python中应用函数列表中的对象

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

问题描述

是否有任何干净的方法可以在没有lambda或列表解析的情况下在Python中的对象上应用函数列表?像Haskell表达式一样:

$ $ p $ $ $ $ $ $ $ $ $ $ $ $ $



Python中的lambda示例:

  response = map(lambda foo:foo(obj),[foo1,foo2])#fooX:object-> Bool 

可扩展到类函数吗?



也许是来自运算符或itertools的东西?

解决方案

我认为这应该符合你的'功能性'标准,为了回答你的问题,我不认为有一个干净的方式,你应该适应列表理解。



如@JFSebastian建议

 >>> from operator import methodcaller 
>>> funcs =(lambda x:x + 1,lambda x:x + 2)
>>> obj = 5
>>> map(methodcaller('__ call__',obj),funcs)
[6,7]

这是一个疯狂的做法:

 >>>从itertools导入starmap,重复
>>> 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]

如@AleksiTorhamo建议

 >>> from itertools import repeat 
>>> from types import FunctionType
>>> obj = 5
>>> funcs =(lambda x:x + 1,lambda x:x + 2)
>>> map(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
>>> 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)
>>> map(FunctionType.__call__, funcs, repeat(obj))
[6, 7]

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

08-20 06:32