Home > Mobile >  Finding List index differences with special number setting
Finding List index differences with special number setting

Time:07-06

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?

CodePudding user response:

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]

  • Related