将数字列表转换为范围

Mar*_*ing 9 python

我有一堆数字,说如下:

1 2 3 4  6 7 8  20 24 28 32
Run Code Online (Sandbox Code Playgroud)

这里提供的信息可以用Python表示为范围:

[range(1, 5), range(6, 9), range(20, 33, 4)]
Run Code Online (Sandbox Code Playgroud)

在我的输出中,我写了1..4, 6..8, 20..32..4,但这只是一个介绍问题.

另一个答案显示了如何为连续范围做到这一点.我不知道如何轻松地为上面的跨栏范围做这件事.对此有类似的伎俩吗?

Jar*_*uen 4

这是解决该问题的直接方法。

def get_ranges(ls):
    N = len(ls)
    while ls:
        # single element remains, yield the trivial range
        if N == 1:
            yield range(ls[0], ls[0] + 1)
            break

        diff = ls[1] - ls[0]
        # find the last index that satisfies the determined difference
        i = next(i for i in range(1, N) if i + 1 == N or ls[i+1] - ls[i] != diff)

        yield range(ls[0], ls[i] + 1, diff)

        # update variables
        ls = ls[i+1:]
        N -= i + 1
Run Code Online (Sandbox Code Playgroud)