Python编程计算列表中1连续出现的次数

Python请写一程序产生一新序列,将由0和1所组成的数列,改为若连续出现1,则写出连续几次,若是0则保持0。
例如若01数列为1, 1, 0, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0 ....则新序列变成2, 0, 1, 0, 0, 4, 0, 0, 0, 1, 0, ....

怎么用Python写代码求这个??

  • 代码运行效果截屏图片

    img

-代码

#!/sur/bin/nve python
# coding: utf-8

lis = [1,1,0,1,0,0,1,1,1,1,0,0,0,1,0] # 预期输出:[2,0,1,0,0,4,0,0,0,1,0]
print(f"\n列表:{lis}\n预期输出:[2, 0, 1, 0, 0, 4, 0, 0, 0, 1, 0]")
newlis = []
count = 0
print(f"\n{' 遍历过程 ':~^37}\n")

for i in range(len(lis)):

    if lis[i]:
        count += 1
    elif not lis[i]:

        if count:
            newlis.append(count)
            count = 0

        newlis.append(0)
    else:
        newlis.append(i)
        count = 0

    print('当前元素:', lis[i], ',新列表:', newlis)

if lis[i]:
    newlis.append(count) # 收集最后的1。

print(f"\n{' 遍历完成 ':~^37}\n")
print('\n实际输出:', newlis)


方法1:利用str类型对连续的1进行切分

a = [1,1,0,1,0,0,1,1,1,1,0,0,0,1,0]
b=[str(x) for x in a]
c=''.join(b)
d=c.replace('01','0 1').replace('10','1 0')
e=d.split()
f=[str(len(x)) if '1' in x else x for x in e]
g=''.join(f)
h=g.replace('',' ').split()
result=[int(x) for x in h]
print(result)

方法2:直接循环

a = [1,1,0,1,0,0,1,1,1,1,0,0,0,1,0]
for i in range(len(a)-1,-1,-1):
    if a[i] and a[i-1]: #如果连续两个都不是0,将值合并,删掉一个
        a[i-1]+=a[i]
        del a[i]
print(a)