如何从Python上的列表中删除字典索引?

时间:2015-03-14 19:20:46

标签: python list dictionary pickle pop

我正在制作一个程序,将高分的玩家存放在游戏厅中。 我正在使用的列表被称为PlayerID,因为它包含唯一ID和其他信息,例如每个游戏中的高分。每当我尝试从播放器列表中成功删除字典时,它都无法正常工作,删除多个配置文件。

这是我目前正在使用的代码。 Pickle正被用于数据存储。

with open("playerdata.dat",'rb') as f:
    PlayerID = pickle.load(f)    
while True:
    try:
        SearchID= int(input("Enter the ID of the profile you are removing")) # used to check if a wanted user actually exists in the program
    except ValueError:
        print("You have not provided an integer input, please try again.") #performs type check to ensure a valid input is provided
        continue
    else:
        break    

index= 0
position = -1
for Player in PlayerID:
    if Player['ID'] == SearchID:
        position = index
    else:
        index = index + 1
    try:
        PlayerID.pop(position)
    except IndexError:
        print("The ID provided does not exist.")
print("The user with ID", searchID,", has been deleted")    
with open('playerdata.dat','wb') as f:
    pickle.dump(playerID,f,pickle.HIGHEST_PROTOCOL)

即使输入的Integer ID实际上不存在于PlayerID列表中,即使我有IndexError代码,它仍会删除多个配置文件。

2 个答案:

答案 0 :(得分:2)

这可能是一种更简单的方法:

for index, Player in enumerate(PlayerID):
    if Player['ID'] == SearchID:
        PlayerID.pop(index)
        print("The user with ID", SearchID, ", has been deleted")
        break
else:
    print("The ID provided does not exist.")

答案 1 :(得分:2)

问题是-1是Python中的有效列表索引;它会弹出列表中的最后一个元素。

一旦遇到正确的id,就更容易弹出。此外,您可以使用enumerate来计算索引:

for index, player in enumerate(players):
    if player['ID'] == search_id:
        players.pop(index)
        # we expect that the ID is truly unique, there is
        # only 1 occurrence of the ID.
        break

现在当然有人可能会问,你为什么不使用id->播放器的字典来存储玩家 - 然后你可以这样做:

if search_id in players:
    players.pop(search_id)