开发者

Python comparison functions

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)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜