如果您正在寻找一种有效的方法来做到这一点,您可以在 C 中做到这一点。这个函数会这样做并返回一个元组数组(位置、长度)。
static PyObject *
bitarray_searchOnes(bitarrayobject *self)
{
idx_t p = 0;
idx_t s = 0;
PyObject *list = PyList_New(0);
while (p < self->nbits) {
if (GETBIT(self, p) == 1) {
s+=1;
}
else {
if (s != 0) {
PyList_Append(list, (PyTuple_Pack(2,PyLong_FromLongLong(p-s),PyLong_FromLongLong(s))));
s=0;
}
}
p++;
}
if (s != 0) {
PyList_Append(list, (PyTuple_Pack(2,PyLong_FromLongLong(p-s),PyLong_FromLongLong(s))));
s=0;
}
return list;
}
您可以将其添加到源中的_bitarray.c 并在bitarray_methods 中定义它。你将在 python 中拥有a.searchOne()。
编辑:更简单的方法是在 python 中遍历位数组。
def searchOnes(bitarray)
s=0
ind=0
arr=[]
for i in bitarray:
if i:
s+=1
elif s:
arr.append((ind-s,s))
s=0
ind+=1
if(s):
arr.append((ind-s,s))
return arr
但是在对 23,000,000 位进行一些基准测试之后,这种方法在我的 intel i7 机器上平均占用了大约 3.6 seconds,而 c 实现只占用了 1 second。
编辑:这就是我做基准测试的方式:
from bitarray import bitarray
from timeit import timeit
from random import choice
def test_searchOnes():
ba=bitarray(''.join(choice('01') for _ in xrange(23000000)))
print timeit(lambda:searchOnes(ba),number=1) # the python version
print timeit(lambda:ba.searchOnes(),number=1) # the C version
结果是:
3.37723302841 # the python version
0.754848003387 # the C version