Re: Want to Use filter() with multi-variable function

Craig Lawson (claw@rahul.net)
Wed, 27 Jul 1994 17:59:49 GMT

Jeffrey Templon (templon@paramount.nikhefk.nikhef.nl) wrote:
: I wanted to do something like:
:
: def checklims(a,b,c) :
: if a >= b and a < c :
: return 1
: else :
: return 0
: newlist = filter(checklims,oldlist)
:
: The problem is (as far as I can tell) that filter expects to get
: a one-parameter function, and supplies each element of that list
: as a parameter, one by one. So how do I tell "checklims" which
: limits to use??

You will need to define a "checklims" function such that it carries around
extra information. It needs a context, which dictates an object.

class context:
def __init__(self, low, high):
self.low, self.high = low, high
def compare(self, x):
return self.low <= x < self.high

def my_filter(l, low, high):
return filter(context(low, high).compare, l)

Now you can write:
newlist = my_filter(oldlist, low_bound, high_bound)

An alternative is to construct and evaluate the call to filter at runtime:
def my_filter(l, low, high):
return eval('filter(lambda x: ' + str(low) + ' <= x < ' +
str(high) + ', l)')

-- 
Craig Lawson
claw@rahul.net