【问题标题】:How do I remove a dictionary index from a list on Python?如何从 Python 列表中删除字典索引?
【发布时间】:2015-03-14 19:20:45
【问题描述】:

我正在创建一个程序,将玩家的高分存储在街机中。 我为此使用的列表称为 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 代码,它仍会删除多个配置文件。

【问题讨论】:

    标签: python list dictionary pickle


    【解决方案1】:

    这可能是实现此目的的更简单方法:

    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.")
    

    【讨论】:

    • 我需要使用 Index = 0 的预定义值还是将 index 读取为它自己的值?
    • 不,所写的for 循环将导致index 从0 开始。您不必自己设置。
    • 我刚刚注意到您的代码,if 语句中的“foundID”是否意味着它的末尾有一个“= True”?
    • 不,没必要。 if 语句后面需要一个布尔值,foundID 是一个布尔值。如果foundID 为True,则if 语句的主块执行,如果foundID 为False,则执行else 块。
    • 很抱歉,但在此解决方案之后又出现了另一个错误。该代码似乎只想删除字面上索引 0 处的字典。
    【解决方案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->player 的字典来存储玩家 - 然后你可以这样做:

    if search_id in players:
        players.pop(search_id)
    

    【讨论】:

    • 我已经尝试合并你的第一种方法,但它似乎根本没有从 playerdata.dat 文件中删除想要的字典
    • 在这种情况下,这可能意味着 search_id 与您文件中的 ID 不匹配;也许你用strs 来表示id,但现在输入了一个int
    • ID 是随机的,通过 randint() 函数生成。该程序似乎只是拒绝删除包含我要删除的 ID 的列表
    猜你喜欢
    • 2018-04-10
    • 2019-09-16
    • 1970-01-01
    • 1970-01-01
    • 2013-09-01
    • 2023-01-08
    • 2021-02-27
    • 2020-07-14
    • 2020-01-13
    相关资源
    最近更新 更多