Python sequence lists

Asked

Viewed 52 times

2

I have a reference list with repeat values ex:. [1, 1, 2, 2, 2, 3, 3, 3, 3, 3, 3].

I am trying to create another list that creates an increasing sequence from the first set of data, restarting the count when another value appears.

Explaining better: in the reference list there is twice the value 1 (at position 0 and 1), then in the final list I want it to appear, the values 1 and 2 in these same positions; when changing the reference list number, the count should resume.

Therefore, the result must be [1, 2, 1, 2, 3, 1, 2, 3, 4, 5, 6].

I’m using the code below:

lista_referencia= [1, 1, 2, 2, 2, 3, 3, 3, 3, 3, 3]
localizador = 0
contador = 0
for i in lista_referencia:
    if i != lista_referencia[localizador - 1]:
        print(1)
    else:
        x = 2 + contador
        print( x, 'arrumar') # arrumar é onde não consigo por a sequência
        contador += 1
    localizador += 1

1 answer

3


I haven’t tried to understand your code, but it seems to me you’re complicating things for no reason.

Just make a loop and save a reference to the previous element. When the current element is the same as the previous one, increment the counter. If different, the counter goes back to 1.

Remember that you are not generating a new list, you are only printing the values. So create this list and add the counts in it:

lista_referencia= [1, 1, 2, 2, 2, 3, 3, 3, 3, 3, 3]

contagens = []
anterior = None # no início não tem anterior
contador = 1
for n in lista_referencia:
    if n == anterior: # elemento atual igual ao anterior, incrementa o contador
        contador += 1
    else: # mudou o número, reinicia o contador
        contador = 1
    # adiciona o contador na lista
    contagens.append(contador)
    # atualiza o anterior
    anterior = n

print(contagens) # [1, 2, 1, 2, 3, 1, 2, 3, 4, 5, 6]

Maybe it’s a bit much for this case, but anyway, it’s also possible to use the module itertools:

from itertools import groupby, count, chain

def nums(items): # obtém os números de 1 até o tamanho do iterável
    return [ i for i, _ in zip(count(1), items) ]

lista_referencia= [1, 1, 2, 2, 2, 3, 3, 3, 3, 3, 3]
contagens = list(chain.from_iterable(nums(run) for _, run in groupby(lista_referencia)))
print(contagens) # [1, 2, 1, 2, 3, 1, 2, 3, 4, 5, 6]

Basically, groupby groups consecutive elements equal. Then the function nums gets a list of 1 up to the amount of numbers in each group, then we generate a list for repetitions of 1, another for repetitions of 2, etc.

And finally, chain.from_iterable creates a single iterable from all these lists, and I put everything on a single list.

As I said, somewhat exaggerated, since the first option seems to me simpler (to do and to understand). But it remains there as curiosity.


Note: what happens if we have a list like [1, 1, 2, 2, 2, 3, 3, 3, 3, 3, 3, 1, 1]? Notice that there are two sequences of 1, then the result with the above codes will be [1, 2, 1, 2, 3, 1, 2, 3, 4, 5, 6, 1, 2] - ending with 1, 2, for every sequence of 1 is counted separately.

Already the another answer (which has been deleted) results in [1, 2, 3, 4, 1, 2, 3, 1, 2, 3, 4, 5, 6], because she considers the total count of 1, even if they are not all consecutive.

Of course, if these cases don’t occur, then whatever.

Browser other questions tagged

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