简体   繁体   English

使用'/'大于小于Python?

[英]Using '/' as greater than less than in Python?

I recently got into code golfing and need to save as many characters as possible. 我最近进入了高尔夫代码,需要尽可能多地保存字符。

I remember seeing someone say to use if a/b: instead of if a<=b: . 我记得看到有人说if a/b:使用if a/b:而不是if a<=b: . However, I looked through Python documentation and saw nothing of the sort. 但是,我查看了Python文档并没有看到任何类似的东西。

I could be remembering this all wrong, but I'm pretty sure I've seen this operator used and recommended in multiple instances. 我可能记得这一切都错了,但我很确定我已经看过这个运算符在多个实例中使用和推荐。

Does this operator exist? 这个运营商是否存在? If so, how does it work? 如果是这样,它是如何工作的?

That's just division. 那只是分裂。 And, at least for integers a >= 0 and b > 0 , a/b is truthy if a>=b . 并且,至少对于整数a >= 0b > 0 ,如果a>=b ,则a/b是真实的。 Because, in that scenario, a/b is a strictly positive integer and bool() applied to a non-zero integer is True . 因为,在那种情况下, a/b是严格正整数,并且应用于非零整数的bool()True

For zero and negative integer arguments, I am sure that you can work out the truthiness of a/b for yourself. 对于零和负整数参数,我相信你可以为自己计算出a/b的真实性。

>>> 5/6
0
>>> bool(5/6)
False

>>> 6/5
1
>>> bool(6/5)
True

It's a result of the / operator in Python 2.7 doing integer division, then converting the result to a boolean. 它是Python 2.7中的/运算符进行整数除法,然后将结果转换为布尔值的结果。

If you do from __future__ import division , this won't work anymore because the / operator will do floating point division rather than integer division. 如果from __future__ import division ,这将不再起作用,因为/运算符将执行浮点除法而不是整数除法。

So the result will still be > 0 for x < y and will still evaluate to True. 因此,对于x < y ,结果仍将> 0 ,并且仍将评估为True。

>>> from __future__ import division

>>> 5/6
0.8333333333333334
>>> bool(5/6)
True

>>> 6/5
1.2
>>> bool(6/5)
True

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM