在列表中查找连续数字组 [英] Finding groups of contiguous numbers in a list
本文介绍了在列表中查找连续数字组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是此的重复问题,用于R而不是Python.
This is a duplicate question to this, except for R rather than Python.
我想在列表中标识出连续的整数组(有些人称它们为连续的),其中重复的条目被视为存在于同一范围内.因此:
I'd like to identify groups of contiguous (some people call them continuous) integers in a list, where duplicate entries are treated as existing within the same range. Therefore:
myfunc(c(2, 3, 4, 4, 5, 12, 13, 14, 15, 16, 17, 17, 20))
返回:
min max
2 5
12 17
20 20
尽管任何输出格式都可以.我当前的蛮力for循环方法非常慢.
Although any output format would be fine. My current brute-force, for-loop method is pretty slow.
(很抱歉,如果我能轻松地重新解释Python答案并且我很愚蠢!)
(Apologies if I could have easily re-interpreted the Python answer and I'm being stupid!)
推荐答案
只需使用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
这篇关于在列表中查找连续数字组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文