简体   繁体   English

计算列表中连续相同值的数量

[英]Compute the number of consecutive identical values in a list

I have a list of binary values: 1 = syncable, 0 =unsyncable. 我有一个二进制值列表:1 =可同步,0 =不同步。 Each binary value represents whether or not a person was syncable that day. 每个二进制值表示一个人当天是否可以同步。

person1=[1,1,0,1,1,0,1,1,1]

I want to make another list, calculating how many days a person was syncable consecutively. 我想列出另一个清单,计算一个人可以连续同步多少天。 When a 0 appears, the counter basically resets. 当出现0时,计数器基本上会复位。

So for the example above, the output would look like: 因此,对于上面的示例,输出如下所示:

person1=[1,2,0,1,2,0,1,2,3]

My issue is whenever the list comes across a 0. I don't know how to get it to reset. 我的问题是,只要列表遇到0,我都不知道如何重置它。 I've tried several ways, none of which works. 我尝试了几种方法,但都无济于事。

x=[1,1,1,1,1]
y=[]

for index, value in enumerate(x):
     y.append(value+sum(x[:index]))

print(y)
...

[1, 2, 3, 4, 5]

Any help is appreciated. 任何帮助表示赞赏。 I think using recursion might help. 我认为使用递归可能会有所帮助。

Do this: 做这个:

i = 0
y = []
for value in person1:
    if value:
        i += 1
    else:
        i = 0
    y.append(i)

There is no reason to create a list of ones. 没有理由创建一个列表。 You just need to keep track of a counter. 您只需要跟踪柜台。

Using itertools.groupby , you could generate a list with sum of syncs. 使用itertools.groupby ,您可以生成一个包含同步总和的列表。

import itertools

person1=[1,1,0,1,1,0,1,1,1]
syncs = [sum(v) for _, v in itertools.groupby(person1)]

Output: 输出:

[2, 0, 2, 0, 3]

And if you just want to get the most consecutive days the person was "syncable", just do: 而且,如果您只是想让人们连续几天都可以“同步”,请执行以下操作:

max_syncs = max[sum(v) for _, v in itertools.groupby(person1) if _]

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

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