Repeat index by giving list
Question:
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]
Answers:
Not the cleanest way to do it but with only built-ins I got the answer with this:
Mylist = [3, 3, 6, 6, 6, 8, 8]
expect = [0]
for i, n in enumerate(Mylist[1:], 1):
expect.append(expect[i-1] if n == Mylist[i-1] else i)
print(expect)
Output:
[0, 0, 2, 2, 2, 5, 5]
Try:
lst = [3, 3, 6, 6, 6, 8, 8]
tmp = 0, -1
out = [tmp[0] if tmp[1] == t[1] else (tmp := t)[0] for t in enumerate(lst)]
print(out)
Prints:
[0, 0, 2, 2, 2, 5, 5]
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]
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]
Not the cleanest way to do it but with only built-ins I got the answer with this:
Mylist = [3, 3, 6, 6, 6, 8, 8]
expect = [0]
for i, n in enumerate(Mylist[1:], 1):
expect.append(expect[i-1] if n == Mylist[i-1] else i)
print(expect)
Output:
[0, 0, 2, 2, 2, 5, 5]
Try:
lst = [3, 3, 6, 6, 6, 8, 8]
tmp = 0, -1
out = [tmp[0] if tmp[1] == t[1] else (tmp := t)[0] for t in enumerate(lst)]
print(out)
Prints:
[0, 0, 2, 2, 2, 5, 5]
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]