Home > front end >  How to remove every 12 zeros from a list
How to remove every 12 zeros from a list

Time:05-10

I have a list as follows:

a = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

I would like to remove zeros that repeat 12 times in a row from the list to have the desired output of

a = [1, 1, 0, 0, 1, 1]

I tried using index but soon realized this would also remove zeros that dont repeat 12 times...

index = [0]
new_a = np.delete(a, index)
print(new_a)

CodePudding user response:

Code

Every line can be well understood.

buffer = []
result = []
for n in num:
    if n == 0:
        buffer.append(n)
    if n == 1:
        if len(buffer) < 12:
            result.extend(buffer)
        result.append(n)
        buffer = []
if len(buffer) < 12:
    result.extend(buffer)
[1, 1, 0, 0, 1, 1]

Trick Answer

  • Using the regexp
  • You can learn it at python.re
import re
line = "".join(str(n) for n in num)
ans = re.sub(r"0{12,}", "", t)
res = [int(n) for n in ans]
[1, 1, 0, 0, 1, 1]

CodePudding user response:

This is a perfect job for itertools:

a = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0,
     1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

from itertools import groupby, chain

a = list(chain.from_iterable(G for k,g in groupby(a)
                             if len(G:=list(g))!=12 or k!=0))

output:

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

NB. this requires python's (≥3.8) assignment expression syntax.

How it works.

itertools.groupby will group consecutive values, if the values are not 0 or if the group size is not 12, keep the group. Then chain all groups back to a single list.

Note that the order of the expressions in the test is important. len(G:=list(g))!=12 should be first to ensure it is always evaluated and thus that G is being defined.

CodePudding user response:

Try this, its a generalization so you can delete sequences of n zeroes from the list:

def remove_n_zeroes(lst, n):
    counter = 0
    new_lst = []
    for num in range(len(lst)):
        if lst[num]!=0:
            if counter<n:
                new_lst.extend([0]*counter)
            counter = 0
            new_lst.append(lst[num])
            continue  # keeps the counter from incrementing 
        counter =1
        if counter == n:
            counter = 0
    if counter < n:   # Handles the trailing zeroes
        new_lst.extend([0] * counter)
    return new_lst
  • Related