python 中if else写在一行以及其他简单逻辑符号简单mark

用法一

a, b = 5, 3
if a>b:
    print("a")
else:
    print("b")

用法二

#一行表达式,if(1)return前者
#if(0)returnelse后面
c = a if a>b else b
print(c)

用法三

#二维列表,利用大小判断的0,1当作索引
c= [b, a][a > b]
print(c)

用法四

#利用逻辑运算符进行操作
#利用and 的特点,若and前位置为假则直接判断为假。
#利用 or的特点,若or前位置为真则判断为真。
#如果a<b则and为0 or之后为[b]   c=([b])[0]
#如果a>b则and为1 or之后不计算为[a]   c=([a])[0]
c = (a>b and [a] or [b])[0]
print(c)

# 改编版
c = (a>b and a or b)
print(c)

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

print(111 or 222) #111
print(0 or 222) #222
print('' or 0) # 0

猜你喜欢

转载自blog.csdn.net/qq_41554005/article/details/89055594