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.
Much simpler and solved 100%. Thank you very much.
– Jefferson Alexandre Silva