如何解释double "or" ||和 if 子句中的赋值
How to interpret double "or" || and assignment in if clause
在 stats::bw.nrd0
的函数源代码中,有一个复杂的(对我来说)if
语句:
> bw.nrd0
function (x)
{
if (length(x) < 2L)
stop("need at least 2 data points")
hi <- sd(x)
if (!(lo <- min(hi, IQR(x)/1.34)))
(lo <- hi) || (lo <- abs(x[1L])) || (lo <- 1)
0.9 * lo * length(x)^(-0.2)
}
<bytecode: 0x0000000010c688b0>
<environment: namespace:stats>
与常规运算符|
相比,||
是否需要以特殊方式解释? Where/how 是否正在分配/重新分配 lo
? "long form"怎么写?
完全公开,我试图将此功能翻译成 Python 功能 ,所以如果你能回答这个问题,你也可以为那个问题添加一个更好的答案。
来自帮助文档:
& and && indicate logical AND and | and || indicate logical OR. The
shorter form performs elementwise comparisons in much the same way as
arithmetic operators. The longer form evaluates left to right
examining only the first element of each vector. Evaluation proceeds
only until the result is determined. The longer form is appropriate
for programming control-flow and typically preferred in if clauses.
感谢一些有用的评论,我现在明白这意味着如果 lo == 0
,我们分配给 hi
、abs(x[1])
或 1
中的非首先是零,按照这个顺序。在 Python 中,我们可以写成:
lo = min(hi, iqr/1.34)
lo = lo or hi or abs(x[0]) or 1
或更明确地说:
if not lo:
if hi:
lo = hi
elif abs(x[0]):
lo = abs(x[0])
else:
lo = 1
在 stats::bw.nrd0
的函数源代码中,有一个复杂的(对我来说)if
语句:
> bw.nrd0
function (x)
{
if (length(x) < 2L)
stop("need at least 2 data points")
hi <- sd(x)
if (!(lo <- min(hi, IQR(x)/1.34)))
(lo <- hi) || (lo <- abs(x[1L])) || (lo <- 1)
0.9 * lo * length(x)^(-0.2)
}
<bytecode: 0x0000000010c688b0>
<environment: namespace:stats>
与常规运算符|
相比,||
是否需要以特殊方式解释? Where/how 是否正在分配/重新分配 lo
? "long form"怎么写?
完全公开,我试图将此功能翻译成 Python 功能
来自帮助文档:
& and && indicate logical AND and | and || indicate logical OR. The shorter form performs elementwise comparisons in much the same way as arithmetic operators. The longer form evaluates left to right examining only the first element of each vector. Evaluation proceeds only until the result is determined. The longer form is appropriate for programming control-flow and typically preferred in if clauses.
感谢一些有用的评论,我现在明白这意味着如果 lo == 0
,我们分配给 hi
、abs(x[1])
或 1
中的非首先是零,按照这个顺序。在 Python 中,我们可以写成:
lo = min(hi, iqr/1.34)
lo = lo or hi or abs(x[0]) or 1
或更明确地说:
if not lo:
if hi:
lo = hi
elif abs(x[0]):
lo = abs(x[0])
else:
lo = 1