traverse python int lists by skipping consecutive numbers

Asked

Viewed 380 times

0

Guys, I’m trying to eliminate consecutive numbers in a list of integers. When the list is for example 1,2,3,5,6,7,8,9... it show: 1-3, 5-9 I tried many ways and I arrived at that code:

def apresenta(lst):

for i in lst:
    x = i #1
    a = i+1 #2 
    b = i+2 #3
    c = i+3 #4
    d = i+4 #5
    e = i+5 #6
    f = i+6 #7
    g = i+7 #8
    h = i+8 #9
    z = i+9 #10
    j = i+10 #11
    l = i+11 #12
    m = i+12 #13
    if len(lst) > 2:
        while b > x:
            lst.pop(a)
        while d > b:
            lst.pop(a)
        while f > d:
            lst.pop(e)
        while h > f:
            lst.pop(g)
        while j > h:
            lst.pop(z)
    return lst

when tested on presents([1,2,3,4])

He tells me Indexerror: pop index out of range

Someone can give me a light?

I know this code lacks much logic, but after several attempts I’m lost...

1 answer

2

If I understand your doubt, follow the script to do what you need:

from itertools import groupby, count

l = [1,2,3,4,5,6,8,10,11]

l = list(set(l)) # Remove números duplicados
l.sort() # Ordenar os números

def apresenta(iterable):
  return ','.join(as_range(g) for _, g in groupby(l, key=lambda n, c=count(): n-next(c)))

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])


print(apresenta(l))

The two commented lines can be used or not, depending on your need.

  • Thank you for your reply. The code works well when we have a predefined list l = [], but I want to make this new list skipping nṹmeros in a row to indicate the appearance of words in an index, and I tested this code by pulling the function 'presents' ([1,2,3,4,5,6,8,10,11])' and it doesn’t work, can you explain to me why?

  • Sorry, maybe the code wasn’t so clear, I’ll update it. Anyway if you pass the direct list instead of the 'g' there in the 'presents' it doesn’t work at all, because the sequence is generated by the groupby right ahead.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.