简体   繁体   English

根据另一个列表返回连续出现的列表

[英]Return list with consecutive occurances based on another list

I have a list with the following number:我有一个带有以下编号的列表:

[0, 0, 0, 0, 1, 1, 0, 0, 1]

What I wanna do is count how many consecutive 1s I have and generate a new list like the following one:我想做的是计算我有多少个连续的 1 并生成一个新列表,如下所示:

[0, 0, 0, 0, 1, 2, 0, 0, 1]

Is there a way to do it in a more compact way than this method?有没有比这种方法更紧凑的方法?

lst = [0, 0, 0, 0, 1, 1, 0, 0, 1]
new_lst = []
counter = 0
for i in range(len(lst)):
    if (lst[i] == 1): counter+=1
    else:counter = 0
    new_lst.append(counter)
print(new_lst)

You could take advantage of the walrus operator if you're using python 3.8 or later:如果您使用的是 python 3.8 或更高版本,则可以利用海象运算符

[counter := counter + 1 if v else 0 for v in lst]

or perhaps itertools.accumulate :或者也许itertools.accumulate

[v for v in itertools.accumulate(lst, lambda acc, v:acc + v if v else 0)]

In both case the result is:在这两种情况下,结果都是:

[0, 0, 0, 0, 1, 2, 0, 0, 1]

It's not so much compact than the question solution but it's more clear:它没有问题解决方案那么紧凑,但更清楚:

l = [0, 0, 0, 0, 1, 1, 0, 0, 1]
s = []

occ = 0
for i in l:
    occ = occ+1 if i==1 else 0
    s.append(occ)
print(s)

Output:输出:

[0, 0, 0, 0, 1, 2, 0, 0, 1]

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

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