Search code examples
pythonlistintervals

Trying to calculate amount of occurrences in a list grouped


I'm trying to count the amount of 1's in a list that occurs after each other.

data = [0,4,5,2,-1,-2,5,1,5,3,5]

count = 0
count_list = []
new_count_list = []

for i in data:
    if i > 0:
        count_list.append(1)
    elif i <= 0:
        count_list.append(0)

for number in count_list:
    if number == 0:
        new_count_list.append(count)
        count = 0
    elif number == 1:
        count = count+1

print(count_list)
print(new_count_list)

For some reason the output is only showing:

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


Solution

  • In your code, in the second for loop, new_count_list is updated only when it sees a zero in count_list. Now, since there are 3 zeroes in count_list, 3 entries are there in new_count_list. Final value of count is not updated to the new_count_list. So you just need to append final value of count to new_count_list after the second for loop to get the desired result. new_count_list.append(count) Add this after the second for loop.. Then the output will be [0, 3, 0, 5]