简体   繁体   English

如何解决每次跳过1个值的循环错误?

[英]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. 我正在做一个迷你学校项目,并且收到标题中提到的错误e。 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: 当程序打印变量listaequipa ,我只能在最后一行得到它:

[('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. 使用特殊值(例如None )标记要删除的项目,然后使用filter或列表理解功能一次删除所有项目。

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: 然后for循环将x递增,因此它会删除当前列表中的第二个元素:

['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 :) 希望这可以帮助 :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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