在 Python 中的一行中分配和检查变量?
Assign and check a variable in a single line in Python?
有时,在 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
中省略内部括号可能会导致“警告:使用赋值的结果作为不带括号的条件 [- W括号]")
所以,我想知道 Python 中是否有等效的语法?
天真的方法似乎不起作用:
$ 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
...然而,很长一段时间我也认为 Python 没有三元表达式的语法,但后来发现 it has - 这就是为什么我问这个问题。
直到 Python 3.8,没有办法做到这一点,因为 Python 中的语句没有 return 值,所以在需要的地方使用它们是无效的表达式是预期的。
Python 3.8引入assignment expressions,又叫海象算子:
if mytest := True:
...
if (foo := some_func()) is None:
....
有时,在 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
中省略内部括号可能会导致“警告:使用赋值的结果作为不带括号的条件 [- W括号]")
所以,我想知道 Python 中是否有等效的语法?
天真的方法似乎不起作用:
$ 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
...然而,很长一段时间我也认为 Python 没有三元表达式的语法,但后来发现 it has - 这就是为什么我问这个问题。
直到 Python 3.8,没有办法做到这一点,因为 Python 中的语句没有 return 值,所以在需要的地方使用它们是无效的表达式是预期的。
Python 3.8引入assignment expressions,又叫海象算子:
if mytest := True:
...
if (foo := some_func()) is None:
....