这可能真的很容易做到,但是我想计算python列表中连续正出现的长度。例如,我有一个a,并且我希望返回b:
a=[0,0,1,1,1,1,0,0,1,0,1,1,1,0]
b=[0,0,4,4,4,4,0,0,1,0,3,3,3,0]
我在Counting consecutive positive value in Python array上注意到了类似的问题,但这仅返回连续的计数,而不返回所属组的长度。
谢谢
python大神给出的解决方案
这类似于run length encoding问题,因此我从Rosetta代码页中借鉴了一些想法:
import itertools
a=[0,0,1,1,1,1,0,0,1,0,1,1,1,0]
b = []
for item, group in itertools.groupby(a):
size = len(list(group))
for i in range(size):
if item == 0:
b.append(0)
else:
b.append(size)
b
Out[8]: [0, 0, 4, 4, 4, 4, 0, 0, 1, 0, 3, 3, 3, 0]