can*_*ine 4 r list range contiguous
这是一个重复的问题,这除了对R,而不是Python的.
我想在列表中标识连续的组(有些人称它们是连续的)整数,其中重复的条目被视为在同一范围内存在.因此:
myfunc(c(2, 3, 4, 4, 5, 12, 13, 14, 15, 16, 17, 17, 20))
Run Code Online (Sandbox Code Playgroud)
收益:
min max
2 5
12 17
20 20
Run Code Online (Sandbox Code Playgroud)
虽然任何输出格式都可以.我目前的蛮力,for-loop方法非常慢.
(如果我能轻易地重新解释Python的答案并且我是愚蠢的,那道歉!)
只需使用diff:
x = c(2, 3, 4, 4, 5, 12, 13, 14, 15, 16, 17, 17, 20)
start = c(1, which(diff(x) != 1 & diff(x) != 0) + 1)
end = c(start - 1, length(x))
x[start]
# 2 12 20
x[end]
# 5 17 20
Run Code Online (Sandbox Code Playgroud)