I work in Python and consider the following problem: given a list, for example [1, 0, -2, 0, 0, 4, 5, 0, 3]
, which contains the integer 0 several times, I would like to have indices in these 0 and for each of them, the number of times it appears in the list until another item appears or the list ends.
Given l = [1, 0, -2, 0, 0, 4, 5, 0]
, the function will return ((1, 1), (3, 2), (7, 1))
. The result is a list of tuples. The first element of the tuple is the index (in the list) of this element, and the second is the number of repetitions until another element appears or the list ends.
Naively, I would write something like this:
def myfun(l, x): if x not in l: print("The given element is not in list.") else: j = 0 n = len(l) r = list() while j <= (n-2): count = 0 if l[j] == x: while l[j + count] == x and j <= (n-1): count +=1 r.append((j, count)) j += count else: j += 1 if l[-1] == x: r.append((n-1, 1)) return r
But I was wondering if there would be a nicer (shorter?) Way to do the same.