带参数的Python列表过滤

时间:2011-08-12 20:09:37

标签: python list filter functional-programming

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)

这就是说有没有办法调用foo使a = 1,c = 4,并且b绑定到myList中的值?

3 个答案:

答案 0 :(得分:47)

一种方法是使用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)

答案 1 :(得分:21)

您可以为此目的创建一个闭包:

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]

答案 2 :(得分:-1)

def foo(a,c):
    return lambda b : a < b and b < c

myList = (1,2,3,4,5,6)

g = filter(foo(1,4),myList)