How to find the count of numbers that are less than each element of a list

Issue

I have a list [1,2,3,4,5,6,7], for each element in the list, I need to find the count of a number of elements that are less than the number. For example, the first element is 1 and there are 0 elements in the list that are less than 1, the second number is 2 and there is 1 element less than 2. So basically the output should be [0,1,2,3,4,5,6]. Need to do this in Python. Any help would be appreciated. Below is the code I’ve tried,

lst = [1,2,3,4,5,6,7]
count = 0
final = []
for i in range(len(lst)):
    for j in range(i+1,len(lst)):
        if lst[i] < lst[j]:
            count = count + 1
    final.append(count)
print (final)

Below is the output I got,

[6, 11, 15, 18, 20, 21, 21]

Solution

Try:

lst = [1, 2, 3, 4, 5, 6, 7]

out = [sum(vv < v for vv in lst[:i]) for i, v in enumerate(lst)]
print(out)

Prints:

[0, 1, 2, 3, 4, 5, 6]

Answered By – Andrej Kesely

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published