WhitneyChia
WhitneyChia

Reputation: 796

Python Ranking only part of a list

I want to be able to rank only part of a list and ignore some elements in that list. I want to ignore elements that are -999 and rank the elements that aren't high to low.

For example:

test_cut = [0.18677649597722776, 0.21992417009282958, 0.21001370207789635, -999, -999, -999]

I want to get a result of [3,1,2,0,0,0]

But if I do this, it will rank the -999 also, which I want to have a value of 0 instead.

[sorted(test_cut, reverse=True).index(i) + 1 for i in test_cut]

output:

[3, 1, 2, 4, 4, 4]

Upvotes: 1

Views: 71

Answers (1)

Aza T
Aza T

Reputation: 589

You can put a conditional statement inside of your list comprehension, like the following:

[sorted(test_cut, reverse=True).index(i) + 1 if i != -999 else 0 for i in test_cut]

Upvotes: 1

Related Questions