Neha soni
Neha soni

Reputation: 13

How to take some percentage of values from a list which has been sorted in descending order in python?

I have the below list sorted in descending order. List is:

[717.1573237876664, 182.7371943521783, 159.83445384690813, 51.76429530389303, 45.6779696561034, 30.617835033786744, 28.400451713817905, 25.784283394118074, 19.37917065]

And I have to take some percentage of values from this list say 80% and that must be in order .eg.

Length of the List: 9
then 80% of 9 = 7.2

Take 7 values from the List in sorted order that is considered

[717.1573237876664, 182.7371943521783, 159.83445384690813, 51.76429530389303, 45.6779696561034, 30.617835033786744, 28.400451713817905].

I am not getting how to write the code for it.

Upvotes: 0

Views: 637

Answers (3)

Sushant
Sushant

Reputation: 3669

First, calculate the number of elements you need -

elements = int(len(x) * (percent/100)) # x here is your list and len(x) is the length of your list

Next, splice the old list -

new_list = x[:elements+1]

Since your own list is sorter already, we don't need to sort again. In case you do need to sort the list, see sorted

Also, see how slicing works.

Upvotes: 0

Arkistarvh Kltzuonstev
Arkistarvh Kltzuonstev

Reputation: 6935

Try this :

new_list = old_list[:int(len(old_list)*0.8)]

Upvotes: 0

iz_
iz_

Reputation: 16603

You need to use list slicing:

mylist = [717.1573237876664, 182.7371943521783, 159.83445384690813, 51.76429530389303, 45.6779696561034, 30.617835033786744, 28.400451713817905, 25.784283394118074, 19.37917065]
percent = 80
print(mylist[:int(len(mylist) * percent / 100)])
# [717.1573237876664, 182.7371943521783, 159.83445384690813, 51.76429530389303, 45.6779696561034, 30.617835033786744, 28.400451713817905]

Upvotes: 1

Related Questions