Python 列表过滤与参数

34 投票
3 回答
34116 浏览
提问于 2025-04-16 23:30

在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 个回答

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)

当然可以!请将您想要翻译的内容提供给我,我会帮您用简单易懂的语言进行解释。

69

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

你可以为这个目的创建一个闭包:

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]

撰写回答