Reputation: 431
I would like to get the lowest 10% numbers in the list.
List = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
From the above list, I expect to get the result. result = [1,2] which is the lowest 10% on the list.
Upvotes: 1
Views: 2109
Reputation: 21
mylist=[int(x) for x in range(1,21)]
mylist.sort()
newlist=[]
for i in range(len(mylist)//10): #just index through the 10% elements with this
newlist.append(mylist[i])
print(newlist)
Upvotes: 1
Reputation: 6129
If every elements are unique, you can simply sort and slice the data
l = list(range(1, 21))
number_value_to_get = len(l)//10
print(sorted(l)[:number_value_to_get]
However, in most of the case, this is wrong, you can use the numpy version
import numpy as np
l = np.array(range(1, 21))
threshold = np.percentile(l, 10) # calculate the 10th percentile
print(l[l < threshold]) # Filter the list.
Be aware to need to define if it this is 10% inclusive or not
import numpy as np
l = np.array([1]*20)
threshold = np.percentile(l, 10)
print(l[l < np.percentile(l, 10)]) # Gives you empty list
print(l[l <= np.percentile(l, 10)]) # Gives you full list
Upvotes: 5
Reputation: 5740
Here you go =^..^=
import numpy as np
List = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
percent = 10
values = list(sorted(np.asarray(List, dtype=np.int))[:int(len(List)/(100/percent))])
Output:
[1, 2]
Upvotes: 2
Reputation: 7510
If you want to use numpy there is a built in percentile function:
import numpy
l = numpy.array([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20])
print(l[l < numpy.percentile(l,10)])
Upvotes: 3
Reputation:
# list of values
lstValues = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
# get maximum value out of list values
max = max(lstValues)
# calculate 10 percent out of max value
max /= 10
# print all the elements which are under the 10% mark
print([i for i in lstValues if i <= max])
Upvotes: 1
Reputation: 3669
Try this -
sorted(lis)[:int((0.1 * len(lis)))]
where lis
is your list.
Upvotes: 2