简体   繁体   English

计算 python 列表中的连续数字

[英]count successive numbers in python list

I have a list of 0s and 1s and I want to know how often 0 occures successively.我有一个 0 和 1 的列表,我想知道 0 连续出现的频率。 I wrote a quick and dirty solution.我写了一个快速而肮脏的解决方案。 However, I believe it is slow但是,我相信它很慢

For example例如

a = [0,0,0,1,1,1,0,0,0,1,1,0,0]
def duration(a):   
    b = "".join([str(x) for x in a])
    return [len(x) for x in b.split("1") if len(x)>0]
print(duration(a))

gives the correct output ([3,3,2]).给出正确的 output ([3,3,2])。 I am convinced that there is a much faster way of doing it.我相信有一种更快的方法可以做到这一点。

Thanks,谢谢,

glostas格罗斯塔斯

itertools.groupby

from itertools import groupby

[len([*g]) for k, g in groupby(a) if k == 0]

[3, 3, 2]

As pointed out in Óscar López 's answer, using the syntax list(g) is compatible with older versions of python.正如Óscar López的回答中所指出的,使用语法list(g)与旧版本的 python 兼容。

[len(list(g)) for k, g in groupby(a) if k == 0]

for

result = []
count = 0
something_not_zero = 1
for e in [*a, something_not_zero]:
    if e == 0:
        count += 1
    elif count > 0:
        result.append(count)
        count = 0

result

[3, 3, 2]

A slight variation on @piRSquared's answer (also using itertools.groupby ). @piRSquared 的答案略有不同(也使用itertools.groupby )。 This should work in older versions of Python, too:这也适用于旧版本的 Python:

from itertools import groupby

def duration(a):
    return [len(list(g)) for k, g in groupby(a) if k == 0]

For example:例如:

duration([0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0])
=> [3, 3, 2]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM