你们 Python 会写: if a < b < c :么?

2019-01-15 11:59:35 +08:00
 vexplain
刚刚,Pycharm 中写了: if min < num and num < max:
结果提示:
Simplify chained comparison
This inspection highlights chained comparisons that can be simplified.

就很纳闷, 随机自己手动 ipython 中试了下 1<2<3 结果是 True.
True < 3 也是 True
应该是跟平常一样 True 和 False 分别当做 1,0 处理了吧。
但是平常没有这么写过, 你们会这么写么?
9434 次点击
所在节点    Python
54 条回复
glacer
2019-01-15 12:00:58 +08:00
这样写如果是 -1<0<1 那就应该是 false 了吧
KevinBu
2019-01-15 12:01:24 +08:00
Pycharm 的提示功能很强大😄
hangvane
2019-01-15 12:17:10 +08:00
@glacer 编译器提示可以简化了那应该就是和数学意义一样吧

测试了下
print(-3<-2<-1)
print(2<3<4)
均为 True,无论假设是左结合还是右结合都是正确的
AvenirX
2019-01-15 12:20:43 +08:00
a<b<c 在 python 等同于 a<b and b<c, 而不是 (a<b)<c.
看: https://docs.python.org/3/reference/expressions.html#comparisons

Also unlike C, expressions like a < b < c have the interpretation that is conventional in mathematics.
不同于 C 语言, a<b<c 会被理解为数学公式写法的意思.
aborigine
2019-01-15 12:20:53 +08:00
@glacer #1 试了下是 true
aijam
2019-01-15 12:20:58 +08:00
Comparisons can be chained arbitrarily, e.g., x < y <= z is equivalent to x < y and y <= z
https://docs.python.org/3.7/reference/expressions.html#comparisons
013231
2019-01-15 12:22:31 +08:00
https://docs.python.org/3/reference/expressions.html#comparisons

為什麼不讀文檔呢?

Comparisons can be chained arbitrarily, e.g., x < y <= z is equivalent to x < y and y <= z, except that y is evaluated only once (but in both cases z is not evaluated at all when x < y is found to be false).

Formally, if a, b, c, …, y, z are expressions and op1, op2, …, opN are comparison operators, then a op1 b op2 c ... y opN z is equivalent to a op1 b and b op2 c and ... y opN z, except that each expression is evaluated at most once.
jmc891205
2019-01-15 12:24:32 +08:00
额 很常写啊 很好用的语法糖
loading
2019-01-15 12:26:11 +08:00
不会,我只会写那种傻子都能看懂的,因为我过几天看我的代码就想看智障的一样。
sikariba
2019-01-15 12:32:48 +08:00
我也常写
bikingtarzan
2019-01-15 12:38:23 +08:00
不会,就用普通的格式,不然之后看代码,就在这里卡一下 , = =
goodryb
2019-01-15 12:42:42 +08:00
为啥不好好写成 a < b and b < c,代码不是约简单越好吗,除非性能上有很大差距
lithiumii
2019-01-15 12:52:04 +08:00
@goodryb 对普通人来说,难道不是连起来写更简单吗? a < b and b < c 只是对别的语言的程序写多了的人来说简单吧。
zhy
2019-01-15 12:55:52 +08:00
前两天刚遇到这种提示,当然这种方式更直观
vexplain
2019-01-15 12:56:09 +08:00
@013231 #7 大佬指点的是, 怎么就没去查下文档呢。
BBCCBB
2019-01-15 12:56:55 +08:00
python 里是可以直接写成 a<b<c 这种形式的, 楼上也说了, 和 a<b and b<c 一样的
vexplain
2019-01-15 13:00:57 +08:00
@jmc891205 #8 以前写 java 不能这么写,现在知道了
xieranmaya
2019-01-15 13:01:55 +08:00
这明明是 python 的标准语法,这个语法给我的映像也很深
不过如果是我,我不会写,我怕把这习惯带到其它语言里面去了
vexplain
2019-01-15 13:02:43 +08:00
@BBCCBB #16 嗯嗯,a < b < c 更容易理解。
vexplain
2019-01-15 13:04:31 +08:00

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/527181

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX