https://www.cnblogs.com/xiexiaoxiao/p/7772441.html
https://blog.csdn.net/su_bao/article/details/81484483
https://blog.csdn.net/leavemetomorrow/article/details/90641362
1. 當只有 if 時,列表生成式構造為 [最終表達式 - (范圍選擇 - 范圍過濾)]
>>> [num ** 2 for num in range(10) if num % 2 == 0]
[0, 4, 16, 36, 64]
如果 if 和 for 的位置調換,則會報錯。
>>> [num ** 2 if num % 2 == 0 for num in range(10)]
File "<stdin>", line 1
[num ** 2 if num % 2 == 0 for num in range(10)]
^
SyntaxError: invalid syntax
2. 當同時有 if 和 else 時,列表生成式構造為 [最終表達式 - 條件分支判斷 - 范圍選擇]
>>> [num ** 2 if num % 2 == 0 else 0 for num in range(10)]
[0, 0, 4, 0, 16, 0, 36, 0, 64, 0]
如何 if 和 for 的位置調換,則會報錯。
>>> [num **2 for num in range(10) if num % 2 == 0 else 0]
File "<stdin>", line 1
[num **2 for num in range(10) if num % 2 == 0 else 0]
^
SyntaxError: invalid syntax
官方文檔並沒有提及到這個。我就說一下我的理解方法。
1,python解釋器看到列表生成式會先找關鍵字 for,for 后面的部分是為了篩選需要顯示的數字,for 前面的表達式則是對這些數字進行進一步加工。
2,當只有 if 而沒有 else 時,此時迭代器 range 里面的元素會被篩選,只有偶數才會進行下一步操作;篩選好之后,再進行平方操作。這里if的作用是為了篩選。
3, 當同時有 if 和 else 時,此時迭代器中的所有元素都將會在下一步被處理,然后就是偶數的進行平方,奇數的顯示為0。這里 if 和 else 的作用則是為了進行不同條件下的處理。
因寫多了判斷語句,看着短短的代碼卻占據來好幾行,於是便搜下if-else簡潔的寫法,結果也是發現新大陸
4種:
第1種:__就是普通寫法
a, b, c = 1, 2, 3 if a>b: c = a else: c = b
第二種:一行表達式,為真時放if前
c = a if a>b else b
第三種:二維列表,利用大小判斷的0,1當作索引
c= [b, a][a > b]
第四種:傳說中的黑客,利用邏輯運算符進行操作,都是最簡單的東西,卻發揮無限能量啊
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 and a)
真:a >b and a,
則a > b 為真
假:b,
則 a> b為假
補充:對於and的理解
id_ = '12345' # 判斷長度為5或者為8 if len(id_) == 5 or len(id_) == 8: print(id_, '------') # 相反的表達為非5且非8 if len(id_) != 5 and len(id_) != 8: print(id_, '+++++++')