Luk
Luk

Reputation: 335

How to replace for-loop by comprehension

I have state_array function. If if state ist true, i'm deleting item from list result. It's not working because for-loop ist out of range. I wat to fix it, and want to ask, it is possible to have list comprehension instead of 'for-loop', if yes, how to do that ?

def state_array(self):
    for k in range(len(result)):
        if '[0]' in str(result[k]):
            if '[7]' in str(result[k+7]) and '[8]' not in str(result[k+8]):
                result[k][0] = str(result[k][0]).replace('[0]', '').replace('X0', 'X0,8')                      # state array
                del result[k+1:k+7]
            else:
                continue

My input:

V;3;M_BB01_03[0];SPPP.BK1800.58,X0;RW
V;3;M_BB01_03[1];SPPP.BK1800.58,X1;RW
V;3;M_BB01_03[2];SPPP.BK1800.58,X2;RW
V;3;M_BB01_03[3];SPPP.BK1800.58,X3;RW
V;3;M_BB01_03[4];SPPP.BK1800.58,X4;RW
V;3;M_BB01_03[5];SPPP.BK1800.58,X5;RW
V;3;M_BB01_03[6];SPPP.BK1800.58,X6;RW
V;3;M_BB01_03[7];SPPP.BK1800.58,X7;RW

And expected output:

V;3;M_BB01_03[0];SPPP.BK1800.58,X0,8;RW

Upvotes: 0

Views: 164

Answers (2)

Arnaud De Broissia
Arnaud De Broissia

Reputation: 659

Here you have too much logic in this block in order to do a clean list comprehension. I do not say it is impossible to pack it all in a list comprehension, i say it would be badly ugly. To prevent your out of range error, just replace range(len(result)) by enumerate(result).

def state_array(self):
for k, r in enumerate(result):
    if k+7 >= len(result):
        break
    if '[0]' in str(r):
        if '[7]' in str(result[k+7]) and '[8]' not in str(result[k+8]):
            r[0] = str(r[0]).replace('[0]', '').replace('X0', 'X0,8')                      # state array
            del result[k+1:k+7]
        else:
            continue

Upvotes: 1

klutt
klutt

Reputation: 31469

You loop from 0 to the original length of the array, but then you change the actual length within the loop. A quickfix to this is to use a while loop:

k=0
while(k<len(A)):
    if(condition)
         del(A[k])
    k=k+1

Upvotes: 1

Related Questions