我對 Python 很陌生,在測驗我的代碼時遇到了一個奇怪的行為。我正在搜索一棵樹并收集資訊,具體取決于我搜索樹的方向。
def my_func():
return (10,20)
direction = 'forward'
if direction == 'forward':
a, b = my_func()
else:
a, b = 30,40
print (f'Direction is: {direction}\nThe value of a is: {a} \nThe value of b is: {b}')
這給了我預期的結果:
Direction is: forward Direction is: backward
The value of a is: 10 The value of a is: 30
The value of b is: 20 The value of b is: 40
但是,如果我使用單行 if-else-condition 結果很奇怪:
a, b = my_func() if direction == 'forward' else 30,40
這給了我以下結果:
Direction is: forward Direction is: backward
The value of a is: (10, 20) The value of a is: 30
The value of b is: 40 The value of b is: 40
誰能向我解釋為什么在這種情況下解包不起作用(前向搜索)以及為什么 b 從 else 分支獲取值?
uj5u.com熱心網友回復:
這并不意外。您設定a為my_func() if direction == 'forward' else 30和b。40這是因為解包是在三元運算子之前完成的。因此,aif else 條件將采用一行的結果,b并將采用 value 40。
如果您想修復它,請執行a, b = my_func() if direction == 'forward' else (30, 40)
編輯:感謝@Jake,他在我編輯的同時發表了評論。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/463108.html
