简体   繁体   中英

Compute the number of consecutive identical values in a list

I have a list of binary values: 1 = syncable, 0 =unsyncable. 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.

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

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 _]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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