Skip to content
Advertisement

Get Indeces of list of numbers Top N, next top N, and last top N

Given that I have a list of numbers:

raw_list = [10, 9, 2, 8, 1, 3, 5, 4, 6, 7,11]

I want to separate it to top N’s three times. Which means I want to rank them.

# Top 6 rank as 3
# Next Top 4 rank as 2
# Last Top 1 rank as 1

ranked_list = [3, 3, 2, 3, 1, 2, 2, 2, 3, 3, 3]

What I tried:

sorted(range(len(raw_list)), key=lambda i: raw_list[i])[-2:]

But this only gives indeces of the topmost and not the next topmost value of the list.

Advertisement

Answer

Use:

lst = [10, 9, 2, 8, 1, 3, 5, 4, 6, 7, 11]
indices = sorted(range(len(lst)), key=lambda i: lst[i], reverse=True)
ranked_list = [0 for _ in range(len(lst))]
for i, j in enumerate(indices):
    if i < 6:
        ranked_list[j] = 3
    elif i < 6 + 4:
        ranked_list[j] = 2
    else:
        ranked_list[j] = 1

print(ranked_list)

Output

[3, 3, 2, 3, 1, 2, 2, 2, 3, 3, 3]
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement