Search code examples
pythonlistindexingcsr

Repeat index by giving list


Not sure if this kind of question is exist or not. If so, I will delete the post later.

I tried to build a list with repeating index which will follow the list here:

Mylist = [3, 3, 6, 6, 6, 8, 8]

My output should be:

expect = [0, 0, 2, 2, 2, 5, 5]

The index will change when the value in the giving list changes.

I tried the code like this:

z_pts = [0] * (len(z_rows)) 
i_cur = -1
for k in range(len(z_rows)):  
    if z_rows[k] != i_cur:                
       i_cur = z_rows[k]         
       z_pts[i_cur] = k

However, I only could get result like this:

res = [0, 0, 0, 0, 2, 5, 0]


Solution

  • This can be done very simply using a list comprehension.

    my_list = [3, 3, 6, 6, 6, 8, 8]
    
    new_list = [my_list.index(i) for i in my_list]
    
    print(new_list) # [0, 0, 2, 2, 2, 5, 5]