Python If-else 多种写法让你看懂大佬代码

版权声明:知识用于传播,才是真谛,欢迎转载,注明出处就好。 https://blog.csdn.net/GhostintheCode/article/details/84852323

Python If-else 多种写法让你看懂大佬代码

第一种:普通写法

a, b, c = 1, 2, 3
if a>b:

    c = a

else:

    c = b

第二种:常见一行表达式

为真时放if前

a, b, c = 1, 2, 3
c = a  if a >b else b

第三种:二维列表

a, b, c = 1, 2, 3
c = [b,a][a > b]

利用a>b的判断结果,0,1作为[b,a]数组的索引。

第四种:逻辑运算符

c = (a>b and [a] or [b])[0]
# 改编版
c = (a>b and a or b)

利用and的特点,若and前的判断为假则直接判断为假
利用or的特点,若or前的判断为真则判断为真

# 从前往后找,and找假,or找真
# 前真返后,
print(111 and 222)  # 222
# 前假返前
print(0 and 333)  #0

# 若x真【x】, x假,y真【y】,xy假【y】,只有前真返回前
print(111 or 222) #111
print(0 or 222) #222
print('' or 0) # 0

对于c = (a>b and a or b)而言,
若 a>b
  真:
    则1 and a = a
  假:
    则 0 or b = b

猜你喜欢

转载自blog.csdn.net/GhostintheCode/article/details/84852323