[Python] Assignment Expressions 「:=」
- 2022.12.08
- Assignment Expressions Python
NAME := expr
Assign to variables within an expression using the notation.
使用例
if Statement
sex = 0
if sex == 0: print("boy")
⇒ if (sex := 0) == 0: print("boy")
while Statement
例1:讀取檔案
file = open("...")
while True:
line = file.readline()
if not line: break
print(line.strip())
⇒ file = open("...")
while (line := file.readline()): print(line.strip())
例2:輸入密碼
while True:
p = input("Enter the password: ")
if p == "*****": break
⇒ while (p := input("Enter the password: ")) != "*****": continue
錯誤例:
while (p := 0) < n:
...
p += 1
⇒ 無限迴圈
Comprehension 推導式
members = [{"name": "Adam", "age": 23,
"height": 1.75, "weight": 72}, # bmi = 23.51
{"name": "Ben", "age": 17,
"height": 1.72, "weight": 63}, # bmi = 21.30
{"name": "Charlie", "age": 20,
"height": 1.78, "weight": 82}, # bmi = 25.88]
def bmi(info):
height = info["height"]
weight = info["weight"]
return weight / (height ** 2)
fat_guys = {info["name"]: bmi(info)
for info in members if bmi(info) > 24}
※ { ... for ... if ... }
is a Comprehension
bmi() 會被呼叫 4 次 (計算 if 的時候 3 次 + 宣告 dict 時 1 次)
使用 := 解決問題:
fat_guys = {info["name"]: _bmi
for info in members if (_bmi := bmi(info)) > 24}
cannot use assignment expressions with attribute/subscribe
在 walrus operator (:=)
的左邊,只能是 single NAME
請參考 PEP 572 # Differences Between Assignment Expressions and Assignment Statements
Single assignment targets other than a single
NAME
are not supported:
# No equivalent
a[i] = x
self.rest = []
替代例
使用 setattr(object, name, value)
if object.name := value:
if (setattr(object, name, temp := value), temp)[1]:
Last Updated on 2024/12/05 by A1go