我对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条件,结果很奇怪:
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分支获取值吗?