Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

number of values in a list greater than a certain number

Tags:

python

list

I have a list of numbers and I want to get the number of times a number appears in a list that meets a certain criteria. I can use a list comprehension (or a list comprehension in a function) but I am wondering if someone has a shorter way.

# list of numbers j=[4,5,6,7,1,3,7,5] #list comprehension of values of j > 5 x = [i for i in j if i>5] #value of x len(x)  #or function version def length_of_list(list_of_numbers, number):      x = [i for i in list_of_numbers if j > number]      return len(x) length_of_list(j, 5) 

is there an even more condensed version?

like image 728
zach Avatar asked May 10 '12 23:05

zach


People also ask

How to check if all values are greater than any given?

Using all() function we can check if all values are greater than any given value in a single line. It returns true if the given condition inside the all() function is true for all values, else it returns false. # python program to check if all. # values in the list are greater. # than val using all() function.

How to find the first number less than the given value?

Similarly, if you want to find the first number in a list that is less than the given value, just replace ‘<’ with ‘>’ in the formula. Just change the logical operator to < from >.

How to find the first larger/smaller value in a list?

Formula to find the first number in a list that is less than the given value. Just change the logical operator to < from >. It's done. You have the first smallest number in the list. {= INDEX ($B$2:$B$10, MATCH (TRUE,$B$2:$B$10<D2,0))} Now you know how to find the first larger/smaller value in a list.

How do you find the sum of numbers greater than k?

We can return 1 when the number greater than k is found and then compute the summation of is using sum () The combination of sort () and bisect (), can actually perform the task of binary search, and hence getting the index and subtracting the size of list can actually help us get elements that are greater than particular element in the list.


1 Answers

You could do something like this:

>>> j = [4, 5, 6, 7, 1, 3, 7, 5] >>> sum(i > 5 for i in j) 3 

It might initially seem strange to add True to True this way, but I don't think it's unpythonic; after all, bool is a subclass of int in all versions since 2.3:

>>> issubclass(bool, int) True 
like image 141
senderle Avatar answered Oct 17 '22 00:10

senderle