Python 如何快速计算二进制列表中0的数量?

Python 如何快速计算二进制列表中0的数量?,python,Python,对于[0,0,1,0,0,1,1,1,1,1,1,0]这样的数组,有没有一种快速的方法返回0的数量,在本例中是5?谢谢 使用list.count: 以及帮助: >>> help(list.count) Help on method_descriptor: count(...) L.count(value) -> integer -- return number of occurrences of value 使用list.count: 以及帮助: >&g

对于[0,0,1,0,0,1,1,1,1,1,1,0]这样的数组,有没有一种快速的方法返回0的数量,在本例中是5?谢谢

使用list.count:

以及帮助:

>>> help(list.count)
Help on method_descriptor:

count(...)
    L.count(value) -> integer -- return number of occurrences of value
使用list.count:

以及帮助:

>>> help(list.count)
Help on method_descriptor:

count(...)
    L.count(value) -> integer -- return number of occurrences of value

你的选择,无论什么让你晚上睡觉:

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])

你的选择,无论什么让你晚上睡觉:

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])

通过使用数组,您可以将速度提高100倍,这只对大型列表非常重要

这应该比my_list.count0快100倍:


但是,如果您的数据已经被安排为numpy数组,或者您可以在创建数据时设法将其放入numpy数组中,那么它才有帮助。否则,转换my_array=np.arraymy_list会消耗时间。

使用数组可以将速度提高100倍,这只对大型列表非常重要

这应该比my_list.count0快100倍:


但是,如果您的数据已经被安排为numpy数组,或者您可以在创建数据时设法将其放入numpy数组中,那么它才有帮助。否则,转换my_array=np.arraymy_列表会占用时间。

我为问这个问题感到羞愧。@Rock well-从好的方面来说-你不会很快忘记它;我为问这个问题感到惭愧。@Rock well——从好的方面来说——你不会很快忘记的;这里和网上都有很多副本…这里和网上都有很多副本。。。
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])
(my_array==0).sum()