【发布时间】:2020-03-05 00:20:21
【问题描述】:
我正在 R 中寻找一种方法,仅在 if 语句第一次被评估为 TRUE 时在 if 语句中运行块,但即使 if 条件再次为 TRUE,该块也不会再次运行。具体来说,该方法在循环中很有用。 这将是“once”语句(在某些外来语言中如此称呼)。
例子:
for (id in id_list){ # runs over a list of several id's which are random
if (id == "snake"){ # I want to run this block only the first time and NOT each time id == "snake"
# now, do some calculations
# ...
}
# do some other calculations by default for all other runs inside the loop
# ...
}
我也很想知道这在 Python 中是如何工作的。
【问题讨论】:
-
A {break} 会中断循环,但这不是所需的行为,因为应该为所有 id 执行 if 块之外的部分——即使在评估第一个 TRUE 之后也是如此。
标签: r if-statement