How to return the last index of a group in a list Python

Viewed 128

I have a list in following form:

[0, 0, 0, 0, 1, 1, 1, 0.6, 0.6, 0, 0, 0]

each of the items in the list is a small decimal number. I'm looking for a way of returning the last index position of each group. In the above example it would be something like:

0: 3, 1: 6, 0.6: 8, 0: 11

I'm fairly new to python and I don't really know how to approach this

2 Answers

itertools.groupby may be useful here, it deals with pretty much everything except tracking the indices which isn't hard to do yourself:

import itertools

a = [0, 0, 0, 0, 1, 1, 1, 0.6, 0.6, 0, 0, 0]
i = 0
for val, group in itertools.groupby(a):
    for inst in group:
        # each element that is the same in sequence, increment index
        i += 1
    # after the inner for loop i will be the index of the first element of next group
    # so i - 1 is the index of last occurence.
    print(val, i - 1)

If you are particularly clever with enumerate and variable unpacking you can make this super short although less obvious how it's working.

import itertools
from operator import itemgetter

a = [0, 0, 0, 0, 1, 1, 1, 0.6, 0.6, 0, 0, 0]
# still group only by value but now use enumerate to have it keep track of indices
for val, group in itertools.groupby(enumerate(a), itemgetter(1)):
    # this is tuple unpacking, irrelevant is a list of values that aren't the last one, and last is the one we care about.
    [*irrelevent, last] = group
    print(last)

This answer is less intended to say "here's how you should do it" and more "this is some of the things that exist in python", happy coding :)

Try this :

a=[0, 0, 0, 0, 1, 1, 1, 0.6, 0.6, 0, 0, 0]
i=0
while(i<=len(a)):
    if (i == len(a)-1):
        print(str(a[i]) + ":" + str(i))
        break
    if(a[i]!=a[i+1]):
       print(str(a[i])+":"+str(i))
    i=i+1
Related