wgz890813 发表于 2018-1-26 15:00:13

(x < y and [x] or [y])[0]实现三元操作符不是很懂

小甲鱼在例题中提到small = x if (x < y and x < z) else (y if y < z else z) 可以转换为x, y, z = 6, 5, 4
if x < y:
    small = x
    if z < small:
      small = z
elif y < z:
    small = y
else:
    small = z

那么(x < y and or )是转换成什么呢?
我知道顺序是 x<y 然后是and 最后是or 但是最后加一个列表是什么鬼?还有这里面涉及到的切片知识是什么?

BngThea 发表于 2018-1-26 15:27:00

这种写法是因为想要使他通用,对于一个常用的int,float等好像没必要写的这么复杂,
但是如果你想判断两个对象都有多个元素的时候就需要,表示取出第一个元素进行判断

wgz890813 发表于 2018-1-27 12:09:58

>>> (0 < 9 and or )
1
>>> (9 < 2 and or )
2
>>> (1 < 2 and or )
8
>>> (7 < 2 and or )
8
>>> (1 < 2 and or )
0
我举了几个例子明白一些,就是如果x < y 为True,就取,如果x < y 为False,就取. 但是为什么这样取还是不明白
页: [1]
查看完整版本: (x < y and [x] or [y])[0]实现三元操作符不是很懂