gpt4 book ai didi

python - 计算Python列表中的连续数字

转载 作者:行者123 更新时间:2023-11-28 21:31:18 32 4
gpt4 key购买 nike

我有一个 0 和 1 的列表,我想知道 0 连续出现的频率。我写了一个快速而肮脏的解决方案。但是,我认为它很慢

例如

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

给出正确的输出([3,3,2])。我相信有一种更快的方法可以做到这一点。

谢谢

格洛斯塔

最佳答案

itertools.groupby

from itertools import groupby

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

[3, 3, 2]

正如 Óscar López 中指出的的答案,使用语法 list(g) 与旧版本的 python 兼容。

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

对于

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]

关于python - 计算Python列表中的连续数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58511658/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com