Home > Software design >  How to split a list into sublists of 6 zeros in a row and other values
How to split a list into sublists of 6 zeros in a row and other values

Time:05-11

This is the list that I have:

a = [0, 0, 0, 0, 0, 0, 1, 1, 4, 5, 0, 0, 4, 0, 0, 0, 0, 0, 0, 1, 3, 4]

I would like to split the list into sublists of 6 zeros in a row and other values to have the desired output of

a = [[0, 0, 0, 0, 0, 0], [1, 1, 4, 5, 0, 0, 4], [0, 0, 0, 0, 0, 0], [1, 3, 4]]

I tried to convert list to string to use split function and then convert string back to list

b = ''.join(map(str,a))
c = b.split('0'*6)
d = list(map(int, c))

and ended up with invalid literal for int() with base 10: '' error message.

Is this the right way to do it? or is there a different way that doesnt involve switching between list and string to avoid such error message?

CodePudding user response:

The following is a quite crude way of doing it:

a = [0, 0, 0, 0, 0, 0, 1, 1, 4, 5, 0, 0, 4, 0, 0, 0, 0, 0, 0, 1, 3, 4]

output, temp = [], []
while a:
    if a[:6] == [0] * 6:
        if temp:
            output.append(temp)
            temp = []
        output.append([0] * 6)
        a = a[6:]
    else:
        temp.append(a[0])
        a = a[1:]
else:
    if temp:
        output.append(temp)

print(output)
# [[0, 0, 0, 0, 0, 0], [1, 1, 4, 5, 0, 0, 4], [0, 0, 0, 0, 0, 0], [1, 3, 4]]

This will deplete the original list a.

CodePudding user response:

One way to do this is to make a generator that keeps track of the seen zeros so far and seen numbers so far. When you get six zeros, you yield it and any previous numbers. Otherwise move the zeros to the other list.

a = [0, 0, 0, 0, 0, 0, 1, 1, 4, 5, 0, 0, 4, 0, 0, 0, 0, 0, 0, 1, 3, 4]

def six_zeros(l):
    z = []
    nums = []
    for n in l:
        if n != 0:
            nums.extend(z)    # add zeros seen so far
            nums.append(n)    # append the number
            z = []
        else:
            z.append(n)       # append the zero
            if len(z) == 6:   # but you've seen 6 yield them
                if nums:
                    yield nums
                yield z
                nums = []
                z = []
    if nums or z:              # don't forget any left-overs
        nums.extend(z)
        yield nums

list(six_zeros(a))
# [[0, 0, 0, 0, 0, 0], [1, 1, 4, 5, 0, 0, 4], [0, 0, 0, 0, 0, 0], [1, 3, 4]]

CodePudding user response:

I think this might be a simpler way:

a = [0, 0, 0, 0, 0, 0, 1, 1, 4, 5, 0, 0, 4, 0, 0, 0, 0, 0, 0, 1, 3, 4]

six_zeros = [0]*6
b, temp = [], []
for x in a:
    temp.append(x)
    temp_len = len(temp)
    if temp_len >= 6 and temp[-6:] == six_zeros:
        if temp_len > 6:
            b.append(temp[:-6])
        b.append(six_zeros)
        temp.clear()
if temp:
    b.append(temp)

print(b)

Output:

[[0, 0, 0, 0, 0, 0], [1, 1, 4, 5, 0, 0, 4], [0, 0, 0, 0, 0, 0], [1, 3, 4]]
  • Related