带有参数的Python列表过滤 [英] Python list filtering with arguments

查看:101
本文介绍了带有参数的Python列表过滤的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

python中是否有一种方法可以在列表上调用过滤器,其中过滤函数在调用过程中绑定了许多参数.例如,有一种方法可以执行以下操作:

Is there a way in python to call filter on a list where the filtering function has a number of arguments bound during the call. For example is there a way to do something like this:

>> 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中的值?

This is to say is there a way to call foo such that a=1, c=4, and b gets bound to the values in myList?

推荐答案

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

You can create a closure for this purpose:

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]

这篇关于带有参数的Python列表过滤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆