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.
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.
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.
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.
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 .
>>> 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 bool
s are int
s too.
(If you oppose this because you think it isn't clear or pythonic then read this link)
Even shorter, using numpy:
sum(np.array(a)>7)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With