Reputation: 947
I'm writing a function for region growing on an irregular grid: Start in a seed bin, find the neighboring bins, and include them in the set of returned bin indices if a certain requirement is fulfilled. I would like for the requirement to be arbitrary, e.g., '> 2', '>= 2', '== 2', etc.. So the syntax would be:
myregion = get_region(bin_coordinates, bin_values, seed_bin, '> 2')
and the region of neighboring bins, whose values are greater than 2 will be returned.
Essentially I'm looking for the same functionality as in the pandas library, where the following is possible when querying a HDF store:
store.select('dfq',where="A>0 or C>0")
I could of course write some sort of parser with if/else statements to translate '> 2' into code, but I was wondering if there is a more elegant way?
Upvotes: 0
Views: 960
Reputation: 6826
Use a lambda (an anonymous function), e.g. lambda x: x>2. Declare getregion as e.g. getregion(coordinates,values,testfun), and call it by e.g. getregion(thesecoords,thesevalues,lambda x: x>2), then in getregion use the test by e.g. if testfun(value). Choose a better name than testfun, though, one that describes what a result of True means.
Another approach would be to define some 'standard' evaluation functions and pass their name to getregion, e.g.
def gt2(x):
return (x>2)
declare getregion as for lambda example:
def getregion( coordinates, values, testfun ):
...
if testfun(x):
...
and call getregion like this:
getregion(thesecoordinates, thesevalues, gt2 )
HTH Barny
Upvotes: 1