How to see if the list contains consecutive numbers

后端 未结 12 1363
别跟我提以往
别跟我提以往 2021-02-07 12:50

I want to test if a list contains consecutive integers and no repetition of numbers. For example, if I have

l = [1, 3, 5, 2, 4, 6]

It should re

12条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-07 13:22

    The first code removes duplicates but keeps order:

    from itertools import groupby, count
    
    l = [1,2,4,5,2,1,5,6,5,3,5,5]
    
    def remove_duplicates(values):
        output = []
        seen = set()
        for value in values:
            if value not in seen:
                output.append(value)
                seen.add(value)
        return output
    
    l = remove_duplicates(l) # output = [1, 2, 4, 5, 6, 3]
    

    The next set is to identify which ones are in order, taken from here:

    def as_range(iterable):
        l = list(iterable)
        if len(l) > 1:
            return '{0}-{1}'.format(l[0], l[-1])
        else:
            return '{0}'.format(l[0])
    
    l = ','.join(as_range(g) for _, g in groupby(l, key=lambda n, c=count(): n-next(c)))
    

    l outputs as: 1-2,4-6,3

    You can customize the functions depending on your output.

提交回复
热议问题