Ad

Convert From For-loop And While-loop To While-loop And While Loop Python

- 1 answer

for x in range(0,len(b)):
    if x+1 < len(b):
        if b[x][1] == 'B' and b[x+1][1] == 'B':
            a.append([b[x][0], b[x][2]])
        elif b[x][1] == 'B'and b[x+1][1] == 'I':
            kata = b[x][0]
            a = 1
            while True:
                if x+a < len(b):
                    if b[x+a][1] == 'I':
                        kata += ' ' + b[x+a][0]
                        a += 1
                    elif b[x+a][1] == 'B':
                        break
                else:
                    break
            a.append([kata, b[x][2]])
    else:
        if b[x][1] == 'B':
            a.append([b[x][0], b[x][2]])

Can someone help me to convert the for-loop become while-loop? and the while-loop stay while-loop?

Ad

Answer

a for loop of the form

for x in y:
    #code 

can always be turned into a while loop of the form

i=0
while i < len(y):
    x = y[i]        
    #code
    i += 1

since x in your case is just iterating through values 0 to len(b) you can further reduce it down to:

x=0
while x < len(b):       
    #code
    x += 1
Ad
source: stackoverflow.com
Ad