即使复制列表,Python列表迭代/修改问题

时间:2015-10-08 00:27:42

标签: python list python-2.7

我已经审核了很多其他帖子,但我确实理解您在迭代时不想修改列表。我仍然得到可怕的列表。删除(x):x不在列表中'很明显,我仍然试图修改一些我不应该修改的东西,只是无法弄清楚在哪里。

这里首先是函数的一部分,它调用函数执行工作并返回一个列表:

for inn in range(1,7):
    for pos in lstPositions:
    weight = 10
    posAssigned = 0
        while (posAssigned == 0):
            lstPlayers = getWeights(weight,pos,inn)

正如您所看到的,我希望获得返回值的玩家列表。现在这里是函数getWeights。正如您在第二部分中看到的,我首先将lstPlayersFunc复制到lstPlayersTmp并迭代lstPlayersTmp,修改lstPlayersFunc。我在下面粘贴的追溯显示了当我尝试从lstPlayersFunc中删除元素时的问题。

def getWeights(weight,pos,inn):
    lstPlayersFunc = []
    for player in positions:
        if positions[player][pos] == weight:
            lstPlayersFunc.append(player)

lstPlayersTmp = lstPlayersFunc[:]
for player in lstPlayersTmp:
    maxBench = 6 - positions[player]['MaxInn']
    for pos in lstPositions:
        if lineup[str(inn)][pos] == player:
            lstPlayersFunc.remove(player)
        elif positions[player]['MaxInn'] <= cntPos[player]['total']:
            lstPlayersFunc.remove(player)
        elif positions[player]['MaxPitch'] <= cntPos[player]['P']:
            lstPlayersFunc.remove(player)
        elif positions[player]['MaxCatch'] <= cntPos[player]['C']:
            lstPlayersFunc.remove(player)
        elif maxBench <= cntPos[player]['B']:
            lstPlayersFunc.remove(player)

return lstPlayersFunc

回溯:

Traceback (most recent call last):
File "./lineups4.py", line 126, in <module>
posAssign()
File "./lineups4.py", line 93, in posAssign
lstPlayers = getWeights(weight,pos,inn)
File "./lineups4.py", line 76, in getWeights
lstPlayersFunc.remove(player)
ValueError: list.remove(x): x not in list

1 个答案:

答案 0 :(得分:2)

您没有提供足够的代码来确定,但我猜测您多次删除相同的player。你的循环结构如下:

for player in lstPlayersTmp:
    maxBench = 6 - positions[player]['MaxInn']
    for pos in lstPositions:
        # A number of tests any one of which passing removes the player

问题是,如果您点击其中一个测试并且for pos in lstPositions:一个remove,则内部player循环不会终止。猜测时,两个不同的pos值导致通过测试,第二次,您尝试remove player已经消失了。

尝试在该循环中的每个break调用之后添加remove。毕竟,一旦玩家被remove编辑,您就不再关心他们,因此您可以停止检查新pos并转到下一个player。< / p>