+2 votes
in Programming Languages by (8.2k points)
I have a big list of intergers and want to count the number of elements greater than some threshold value. I can use 'for' loop for this task, but is there another approach?

E.g.

 a=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
If I have to count how many elements are greater than 5, it should give 10.

1 Answer

0 votes
by (16.1k points)

You can convert the list to Numpy array and then use Numpy functions to count the elements greater than a particular value. Check the following example.

>>> a=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]

>>> a=np.array(a)

>>> np.count_nonzero(a>5)

10

>>> np.count_nonzero(a<=5)

5

...