if语句有块,而不是值。您似乎将此与三元运算符混淆了。例如,在 Tableau 中,如果您编写
if condition then
x
else
y
end
那么当condition为真时,整个语句将被评估为具有 的值x。如果你写
z = if condition then x else y end
那么只要condition为真,表达式if condition then x else y将被评估为x,因此x将被分配给z。
然而,在 Python 中,如果你写
if condition then:
x
Python 期望x的不是一个值,而是一个指令。在您的第一个示例中,您有im_warped[i][j]=0. 这是一条指令:它告诉 Python 分配0给im_warped[i][j]. 如果你要写
z = if condition:
x
else:
y
这将在 Python 中返回错误,因为在 Python 中 if-then-else 不是三元运算符,它是一个控制语句。它不返回任何值、条件值或默认值。相反,它运行代码。“默认”,在某种程度上,是不运行任何代码。当您编写if x < 0 or x >= ht or y < 0 or y >= wdt: im_warped[i][j] = 0时,返回值的不是if-then-else语句;而是返回值的语句。您在它正在运行的代码中放置了一个0 值。
Python 中有一个三元运算符,但它的语法略有不同:它是conditional_result if condition else default. 所以你的第一个例子可以写成
im_warped[i][j] = 0 if x < 0 or x >= ht or y < 0 or y >= wdt else im[x][y]
如果你要写
im_warped[i][j] = im[x][y] if 0 < x < ht and 0 < y < wdt
如果没有else,那将返回错误。