Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading