简体   繁体   中英

How to fix for loop error skipping 1 value a time?

Im doing a mini school project, and im getting the error e referred in the title. How do i solve my error?

This is for a mini "football manager" project and i know my error is this one line!

equipas=['Napoli','Inter','Milan','Roma','Sampdoria','Atalanta','Lazio','Fiorentina','Torino','Sassuolo','Parma','Genoa','Cagliari','SPAL','Udinese','Empoli','Bologna','Frosinone','Chievo']    
for m in range(0,99):
    try:
        z=equipas[m]
    except IndexError:
        a+=1
        if a==3:
            break
    else:
        equipa=equipas[m]
        equipas.remove(equipa)
        pontos=random.randint(0,57)
        equipa=equipa,pontos
        listaequipa.append(equipa)
        print(listaequipa)

When the program prints the variable listaequipa , I only get this in the final line:

[('Napoli', 44), ('Milan', 57), ('Sampdoria', 31), ('Lazio', 14), ('Torino', 3), ('Parma', 13), ('Cagliari', 51), ('Udinese', 8), ('Bologna', 21), ('Chievo', 38)]

You should not iterate over the indexes of a list and remove elements from it at the same time . That's what's causing the error.

Fortunately you have a couple of alternatives, pick the one that you're more comfortable with:

  • Iterate over the list indexes in reverse, in that way you can remove the elements harmlessly.
  • Create a new list with all the elements except the ones that you're supposed to remove.
  • Mark the items to delete with a special value (say, None ) and afterwards remove all of them at the same time, using filter or a list comprehension.

When you remove an item from a list using

list.remove(item)

It doesn't replace the item with a null value, it removes it completely and the rest of the elements take its place. For example:

array = ['1', '2', '3', '4', '5', '6']
for x in range(5):
    array.remove(array[x])

After the first pass of the loop, the array now looks like:

['2', '3', '4', '5', '6']

and then the for loop increments x so it removes the second element in the current list:

['2', '4', '5', '6']

And so on, skipping every second value of the original list.

So read over your code, and see where this could be happening.

Hope this helps :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM