0

I have an array as follow:

a = [1 2 5 3 8 7 2 9 8]

and a constant number b=4

How can I count the occurrence c of a being inferior to b?

So in this example c=4

steve
  • 511
  • 1
  • 9
  • 33
  • 1
    If it's a numpy array then `(a – pault Jul 03 '19 at 16:24
  • 2
    Possible duplicate of [Numpy mask to count number of elements satisfying a condition](https://stackoverflow.com/questions/49762199/numpy-mask-to-count-number-of-elements-satisfying-a-condition) or [How to count values in a certain range in a Numpy array?](https://stackoverflow.com/questions/9560207/how-to-count-values-in-a-certain-range-in-a-numpy-array) – pault Jul 03 '19 at 16:28
  • It is a numy array – steve Jul 03 '19 at 16:28

2 Answers2

1

Using numpy:

np.sum(a < 4)

Or a sum on generator:

sum(num < 4 for num in a)
Austin
  • 25,759
  • 4
  • 25
  • 48
0

If you mean "less than" by "inferior", you can use a list comprehension

c = len([x for x in a if x < b])

If you're worried about space constraints, you can use a generator like Alexander's answer.

sum(1 if num < b else 0 for num in a)
rma
  • 1,853
  • 1
  • 22
  • 42