Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I count occurrences of elements that are bigger than a given number in an list?

Tags:

python

list

count

Let's say I have this list:

a = [1.1, 2, 3.1, 4, 5, 6, 7.2, 8.5, 9.1]

I want to know how many elements are there bigger than 7. The result should be 3. Is there an elegant way to do this in Python? I tried with count but it won't work.

like image 362
otmezger Avatar asked Apr 02 '13 08:04

otmezger


People also ask

How do you count occurrences in a list?

Using the count() Function The "standard" way (no external libraries) to get the count of word occurrences in a list is by using the list object's count() function. The count() method is a built-in function that takes an element as its only argument and returns the number of times that element appears in the list.

How do you count how many times a value appears in a list?

Count how often a single value occurs by using the COUNTIF function. Use the COUNTIF function to count how many times a particular value appears in a range of cells.

How do you count occurrences in a list in Python?

The easiest way to count the number of occurrences in a Python list of a given item is to use the Python . count() method. The method is applied to a given list and takes a single argument. The argument passed into the method is counted and the number of occurrences of that item in the list is returned.

How do you find the item with the maximum number of occurrences in a list in Python?

Use max() to find the item with the maximum number of occurrences in a list. Call max(iterable, key=None) with iterable as a list and key set to list. count to return the item with the maximum number of occurrences in list .


2 Answers

>>> a = [1.1 , 2 , 3.1 , 4 , 5 , 6 , 7.2 , 8.5 , 9.1]
>>> sum(x > 7 for x in a)
3

This uses the fact that bools are ints too.

(If you oppose this because you think it isn't clear or pythonic then read this link)

like image 167
jamylak Avatar answered Sep 30 '22 01:09

jamylak


Even shorter, using numpy:

sum(np.array(a)>7)
like image 38
Noam Peled Avatar answered Sep 30 '22 00:09

Noam Peled