ksc*_*ttz 22 python functional-programming list filter
在python中是否有一种方法可以在列表中调用过滤器,其中过滤函数在调用期间绑定了许多参数.例如,有没有办法做这样的事情:
>> 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)
Run Code Online (Sandbox Code Playgroud)
这就是说有没有办法调用foo使a = 1,c = 4,并且b绑定到myList中的值?
sen*_*rle 51
一种方法是使用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)
Run Code Online (Sandbox Code Playgroud)
另一种是使用partial:
>>> from functools import partial
>>> filter(partial(foo, 1, c=4), myTuple)
(2, 3)
Run Code Online (Sandbox Code Playgroud)
Zau*_*bov 26
您可以为此目的创建一个闭包:
def makefilter(a, c):
def myfilter(x):
return a < x < c
return myfilter
filter14 = makefilter(1, 4)
myList = [1, 2, 3, 4, 5, 6]
filter(filter14, myList)
>>> [2, 3]
Run Code Online (Sandbox Code Playgroud)