這個問題在這里已經有了答案: Python 中的冒號等于 (:=) 是什么意思? (5 個回答) ":=" 語法和賦值運算式:什么和為什么? (3 個回答) 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
(這似乎是一種標準技術,考慮到在 the 中省略內括號if可能會導致“警告:使用賦值的結果作為沒有括號的條件 [-Wparentheses] ”)
所以,我想知道 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 沒有三元運算式的語法,但后來事實證明,它有- 這就是我問這個問題的原因。
uj5u.com熱心網友回復:
在 Python 3.8 之前,沒有辦法做到這一點,因為 Python 中的陳述句沒有回傳值,因此在需要運算式的地方使用它們是無效的。
Python 3.8 引入了賦值運算式,也稱為 walrus 運算子:
if mytest := True:
...
if (foo := some_func()) is None:
....
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/376328.html
上一篇:如何在tkinter中重繪影像
下一篇:帶有奇怪演算法的Python程式
