这是一个可能有用的lil函数:
def group_consecutives(vals, step=1): """Return list of consecutive lists of numbers from vals (number list).""" run = [] result = [run] expect = None for v in vals: if (v == expect) or (expect is None): run.append(v) else: run = [v] result.append(run) expect = v + step return result>>> group_consecutives(a)[[0], [47, 48, 49, 50], [97, 98, 99]]>>> group_consecutives(a, step=47)[[0, 47], [48], [49], [50, 97], [98], [99]]
PS这是纯Python。有关NumPy的解决方案,请参见unutbu的答案。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)