代码之家  ›  专栏  ›  技术社区  ›  sdbbs

在Python中,在单行中分配和检查变量?[副本]

  •  0
  • sdbbs  · 技术社区  · 3 年前

    有时,在C语言中,我喜欢在同一行上赋值和检查一个条件变量——主要是为了在隔离代码部分(例如,而不仅仅是编写代码)的同时进行自我文档化 if ( 1 ) { ... } ),而无须写 #ifdef . 让我举一个例子:

    #include <stdio.h>
    #include <stdbool.h>
    
    int main() {
        bool mytest;
        if ( (mytest = true) ) {
          printf("inside %d\n", mytest);
        }
        printf("Hello, world! %d\n", mytest);
        return 0;
    }
    

    这就是你所期望的:如果你有 if ( (mytest = true) ) { ,程序的输出为:

    inside 1
    Hello, world! 1
    

    ... 如果你写信 if ( (mytest = false) ) { ,程序的输出为:

    Hello, world! 0
    

    (考虑到在 if 警告:将赋值结果用作不带括号的条件[-wParenthes] ")

    天真的方法似乎不起作用:

    $ python3
    Python 3.8.10 (default, Sep 28 2021, 16:10:42) 
    [GCC 9.3.0] on linux
    Type "help", "copyright", "credits" or "license" for more information.
    >>> mytest = None
    >>> if ( (mytest=True) ): print("inside {}".format(mytest))
      File "<stdin>", line 1
        if ( (mytest=True) ): print("inside {}".format(mytest))
                    ^
    SyntaxError: invalid syntax
    

    it has -这就是为什么我要问这个问题。

    1 回复  |  直到 3 年前
        1
  •  0
  •   Ashwini Chaudhary    3 年前

    在Python3.8之前,没有办法做到这一点,因为Python中的语句没有返回值,所以在需要表达式的地方使用它们是无效的。

    assignment expressions ,也称为海象操作员:

    if mytest := True:
        ...
    
    if (foo := some_func()) is None:
       ....