python if else黑客級寫法

2021-10-14 15:33:34 字數 1005 閱讀 1879

例子:

a, b, c = 1, 2, 3

if a>b:

c = a

else:

c = b

普通人怎麼寫:

c = a if a>b else b
黑客怎麼寫:

c = (a>b and a or b)
解析:巧妙利用 「and」 和「or」 用法,從前往後找,and找假,or找真

首先理解 and,從前往後,有假輸出第乙個假,全真輸出最後真

print( 1 and 2) #2

print(1 and 0) #0

print(0 and 1) #0

'''

從前往後找,and找假

全真返後真

'''print(666 and 999) # 999

'''前假返前

'''print(0 and 999) #0

其次 or,從前往後,有真輸出第乙個真,全假為o(false)

print(1 or 0) # 1

print(0 or 1) # 1

print(0 or 0) # 0

#or找真,全真反前真

print(666 or 999) #999

print(0 or 999) #999

print('' or 0) # 0

理解後,再看 c = (a>b and a or b)

1)假設 a>b, a>b為真

則 a>b and a ,輸出 a,為真

則a or b,輸出 a

結果 c=a

2)假設 ab為假

則a>b and a,輸出 0 

則 0 or b,輸出b

結果 c=a

邏輯很簡單,巧妙運用,不同感覺。

python if else 簡寫 深究

大牛壯壯 python if else的簡寫 1 值 值1 if bool else 值2 2 值 值1,值2 bool 其實就是讀取列表的0元素或1元素 3 值 bool and 值1 or 值2,這個我沒想到和接觸過,我只以為邏輯運算子的結果只是bool 效率 原始if else 方法1,真 方...

Python if else和for的後置用法

if else的後置類似於c 的三目運算子 int a 1 int b 2 int c a b?a b 取得a,b中的較大值儲存在c中 int d a b?a c?a c b c?b c 巢狀寫法,有較多冗餘python a 1 b 2 c a if a b else b if中條件滿足則返回a,否...

Python if else對縮排的要求詳解

前面的 python if else 一節展示了選擇結構的三種基本形式,並給出了例項演示,但是大家在編寫 過程中仍然要注意一些細節,尤其是 塊的縮排,這對 if else 選擇結構極其重要。python 是以縮進來標記 塊的,塊一定要有縮排,沒有縮排的不是 塊。另外,同乙個 塊的縮排量要相同,縮排量...