非常简单的示例代码(仅用于演示,没有任何用处):
repeat {
while (1 > 0) {
for (i in seq(1, 100)) {
break # usually tied to a condition
}
break
}
break
}
print("finished")
我想在不使用的情况下摆脱多个循环break
分别在每个循环中。
根据关于 python 的类似问题,将我的循环包装到函数中似乎是一个可能的解决方案,即使用return()
打破函数中的每个循环:
nestedLoop <- function() {
repeat {
while (1 > 0) {
for (i in seq(1, 100)) {
return()
}
}
}
}
nestedLoop()
print("finished")
R 中还有其他方法吗?也许像标记循环然后指定要中断哪个循环(就像在 Java 中一样)?
使用显式标志,并根据这些标志有条件地跳出循环可以提供更多的灵活性。例子:
stop = FALSE
for (i in c(1,2,3,4)){
for (j in c(7,8,9)){
print(i)
print(j)
if (i==3){
stop = TRUE # Fire the flag, and break the inner loop
break
}
}
if (stop){break} # Break the outer loop when the flag is fired
}
上面的代码将打破两个嵌套循环i=3
。当最后一行(if (stop){break}
) 被注释掉,那么只有内部循环被破坏i=3
,但外循环继续运行,即它实际上跳过了以下情况i=3
。这种结构很容易使用,并且可以根据需要灵活使用。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)