简体   繁体   English

为什么在使用一行 if-else 语句时解包不能正常工作

[英]Why unpacking doesn't work correctly when using an one line if-else statement

I'm very new to Python and came to a strange behaviour while tested my code.我是 Python 的新手,在测试我的代码时出现了一个奇怪的行为。 I'm searching over a tree and gather informations, depending on the direction i'm searching the tree.我正在搜索一棵树并收集信息,具体取决于我正在搜索树的方向。

    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}')

This gives me the expected result:这给了我预期的结果:

    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

But if i use an one-line if-else-condition the result is strange:但是,如果我使用单行 if-else-condition,结果会很奇怪:

    a, b = my_func() if direction == 'forward' else 30,40

This gives me the following result:这给了我以下结果:

    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

Can anyone explain to me why unpacking doesn't work in this case (forward search) and why b gets the value from the else branch?谁能向我解释为什么在这种情况下解包不起作用(正向搜索)以及为什么 b 从 else 分支获取值?

It isn't unexpected.这并不意外。 You set a to my_func() if direction == 'forward' else 30 and b to 40 .您将a设置为my_func() if direction == 'forward' else 30并将b设置为40 This is because the unpacking is done before the ternary operator.这是因为解包是在三元运算符之前完成的。 Thus, a will take the result of the one line if else condition and b will take the value 40 .因此, a将采用一行 if else 条件的结果,而b将采用值40

If you want to fix it, do a, b = my_func() if direction == 'forward' else (30, 40)如果你想修复它,做a, b = my_func() if direction == 'forward' else (30, 40)

EDIT: credit to @Jake, who commented at the same time I edited.编辑:归功于@Jake,他在我编辑的同时发表了评论。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM