Finding List index differences with special number setting

Question:

Suppose I have a Python List like this:

a = [70,66,63,-1,-1,68,-1,70]

By the following code I can get the list of index differences among non-minus-one elements(Since -1 will not appear at the end of the list):

res = [idx for idx, val in enumerate(a) if val != -1]
index_diff = [x - res[i - 1] for i, x in enumerate(res)][1:]

and index_diff looks like this:

[1, 1, 3, 2]

Now I would like to make some adjustments, because there is two -1 between 63 and 68, and one -1 between 68 and 70, I would like to deduct the number of -1 between them, so the target should look like this:

[1,1,1,1]

Anyone can help with this?

Answers:

a = [70,66,63,-1,-1,68,-1,70]
res = [idx for idx, val in enumerate(a) if val != -1]
index_diff = [x - res[i - 1] for i, x in enumerate(res)][1:]

Keep track of the indexes we’ve already traversed and then do the subtraction.

sumx = 0
new_count = []
for x in index_diff:
    if x == 1:
        sumx +=1
        new_count.append(x)
    else:
        new_count.append(x - len(a[sumx+1:sumx+x]))
        
print(new_count)

[1, 1, 1, 1]

Answered By: jonsca
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.