将序列号列表转换为间隔或范围

时间:2019-02-04 05:17:17

标签: python

我有一个这样的列表:

a = [1, 2, 3, 4, 5, 8, 9, 10, 11, 15, 16, 17]

我希望得到的结果是:

b = [1-5, 8-11, 15-17]

因为在我的列表a中,我有依次从1 to 5, 8 to 1115 to 17开始的数字。

我应该如何在Python中做到这一点?

2 个答案:

答案 0 :(得分:2)

itertools.groupby用作described here,但@luca稍有变化:

import itertools

def to_ranges(iterable):
    iterable = sorted(set(iterable))
    for key, group in itertools.groupby(enumerate(iterable),
                                        lambda t: t[1] - t[0]):
        group = list(group)
        yield group[0][1], group[-1][1]


x = [1, 2, 3, 4, 5, 8, 9, 10, 11, 15, 16, 17]
print( list(to_ranges(x)))

输出:

[(1, 5), (8, 11), (15, 17)]

答案 1 :(得分:0)

    def range_extract(lst):
            'Yield 2-tuple ranges or 1-tuple single elements from list of increasing ints'
            lenlst = len(lst)
            i = 0
            while i< lenlst:
                low = lst[i]
                while i <lenlst-1 and lst[i]+1 == lst[i+1]: i +=1
                hi = lst[i]
                if   hi - low >= 2:
                    yield (low, hi)
                elif hi - low == 1:
                    yield (low,)
                    yield (hi,)
                else:
                    yield (low,)
                i += 1

    def printr(ranges):
            print( ','.join( (('%i-%i' % r) if len(r) == 2 else '%i' % r)
                             for r in ranges ) )

    if __name__ == '__main__':
            lst = [1, 2, 3, 4, 5, 8, 9, 10, 11, 15, 16, 17]
            x=range_extract(lst)
            print(list(x))

    # output : [(1, 5), (8, 11), (15, 17)]