Mohamed Nassar
Mohamed Nassar

Reputation: 23

Convert certain numbers which are randomly distributed in a list while leaving others

I have list z, been trying to convert all the 1s to 0s only if they were preceded or followed by 0. The 2s and 4s act as breaks in the sequence, and 1s not attached to 0 should remain 1s. The list y is what I would like to have.

z=[2,1,2,0,1,1,1,2,1,1,2,1,1,1,0,2,0,1,4,1,0,0,1,1,2,0]
y=[2,1,2,0,0,0,0,2,1,1,2,0,0,0,0,2,0,0,4,0,0,0,0,0,2,0]

I can only get all the 1s to be 0s including the ones not attached to 0.

for a in range(len(z)):
    if a==0: 
        startindex=0
    elif a==(len(z)-1):
        ctr+=1
        for i in range(startindex,(len(z))):
            if z[i]==1:
                f=1
                y.append(f)
            else:
                f=z[i]
                y.append(f)
    else:
        for i in range(startindex,a):
            if z[i]==0:
                f=0
                y.append(f)
            elif z[i]==1: 
                f=0
                y.append(f)
            else:
                f=z[i]
                ctr+=1
                y.append(f)
        startindex=a

Thanks.

Upvotes: 1

Views: 24

Answers (1)

Thierry Lathuille
Thierry Lathuille

Reputation: 24242

One way to do it, using itertools.groupby. The idea is, if there is any zero in a sequence of 0 and 1, all will turn to 0, and the other values are left unchanged:

from itertools import groupby

z = [2,1,2,0,1,1,1,2,1,1,2,1,1,1,0,2,0,1,4,1,0,0,1,1,2,0]

out = []
for zero_or_one, group in groupby(z, lambda x: x in {0, 1}):
    values = list(group)
    if zero_or_one:
        if any(x==0 for x in values):
            values = [0]*len(values)
    out.extend(values)


print(out)
# [2, 1, 2, 0, 0, 0, 0, 2, 1, 1, 2, 0, 0, 0, 0, 2, 0, 0, 4, 0, 0, 0, 0, 0, 2, 0]

y=[2,1,2,0,0,0,0,2,1,1,2,0,0,0,0,2,0,0,4,0,0,0,0,0,2,0]
assert out == y  # this is the expected output

Upvotes: 1

Related Questions