python 中有没有一种方法可以在列表中调用过滤器,其中过滤函数在调用期间绑定(bind)了许多参数。例如有没有办法做这样的事情:
>> def foo(a,b,c):
return a < b and b < c
>> myList = (1,2,3,4,5,6)
>> filter(foo(a=1,c=4),myList)
>> (2,3)
也就是说有没有办法调用 foo 使 a=1、c=4 和 b 绑定(bind)到 myList 中的值?
最佳答案
一种方法是使用 lambda
:
>>> def foo(a, b, c):
... return a < b and b < c
...
>>> myTuple = (1, 2, 3, 4, 5, 6)
>>> filter(lambda x: foo(1, x, 4), myTuple)
(2, 3)
另一个是使用partial
:
>>> from functools import partial
>>> filter(partial(foo, 1, c=4), myTuple)
(2, 3)
关于带参数的 Python 列表过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7045754/