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

How do I remove a dictionary index from a list on Python?

我正在创建一个程序,用于存储街机游戏中玩家的高分。 我为此使用的列表称为 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)

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

这可能是完成此任务的更简单方法:

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 是 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->player 的字典来存储玩家 - 那么你可以这样做:

if search_id in players:
    players.pop(search_id)