With an array like [0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 0], is there a quick way to return the number of 0(s), which is 5 in the example? Thanks!
Asked
Active
Viewed 4,988 times
5 Answers
10
Use list.count:
your_list.count(0)
And the help:
>>> help(list.count)
Help on method_descriptor:
count(...)
L.count(value) -> integer -- return number of occurrences of value
Jon Clements
- 132,101
- 31
- 237
- 267
-
4
-
1@Rock well - on the plus side - you won't forget it any time soon ;) – Jon Clements Mar 01 '13 at 07:59
2
In [16]: l = [0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 0]
In [17]: l.count(0)
Out[17]: 5
avasal
- 13,666
- 4
- 29
- 47
1
Your choice, whatever lets you sleep at night:
l = [0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 0]
print l.count(0)
# or maybe:
print len(filter(lambda a: a == 0, l))
# or maybe:
print len([0 for x in l if x==0])
JHolta
- 2,061
- 1
- 27
- 26
1
You can speed things up by a factor of 100 by using arrays (, which only becomes important for large lists)...
This should be 100 times faster than my_list.count(0):
(my_array==0).sum()
However it only helps, if your data is already arranged as a numpy array (or you can manage to put it into a numpy array when it is created). Otherwise the conversion my_array = np.array(my_list) eats the time.
flonk
- 3,387
- 3
- 22
- 34