I have some data that lends itself to开发者_如何学JAVA representation as a value and a comparison function, (val, f)
, so another value can be checked against it by seeing if f(val, another)
is True
. That's easy.
Some of them just need >
, <
, or ==
as f
, however, and I can't find a clean way of using them; I end up writing things like ScorePoint(60, lambda a, b: a <= b)
. That's ugly.
Is there a way I can do something more like ScorePoint(60, <=)
?
The operator
module is your friend:
import operator
ScorePoint(60, operator.le)
See http://docs.python.org/library/operator.html
Yes:
LessEqual = lambda a, b: a <= b
ScorePoint(60, LessEqual)
or more concise (but less readable):
LE = lambda a, b: a <= b
ScorePoint(60, LE)
精彩评论