开发者

Python comparison functions

开发者 https://www.devze.com 2023-01-17 05:48 出处:网络
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.Th

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

精彩评论

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

关注公众号