【问题标题】:delete item from a list value in dictionary Python从字典Python中的列表值中删除项目
【发布时间】:2021-04-17 13:04:30
【问题描述】:

我正在尝试从在字典中设置为值的列表中删除一个项目,字典是一个看起来像这样的 self 对象


    {'battleship': ['A1', 'A2', 'A3', 'A4']}

我保存了一个变量,其中包含要从列表中删除的给定元素:


    shot_pose = "A3"

预期输出:


    {'battleship': ['A1', 'A2', 'A4']}

代码给了我 TypeError ,我的完整代码:


    class Game:
    
        def __init__(self):
    
            self.__dictionary = {'battleship': ['A1', 'A2', 'A3', 'A4']}
    
        def printout(self):
    
            print(self.__dictionary)
    
        def update_dictionary(self):
            shot_pose = "A3"
    
            for positions in self.__dictionary.values():
                for place in positions:
                    if place == shot_pose:
                        del positions[place]
            print(self.__dictionary)
    
    def main():
    
        game = Game()
        game.printout()
        game.update_dictionary()
    
    if __name__ == "__main__":
        main()

稍后在创建程序的其余部分时,这个镜头位置将是用户输入的条目,这就是为什么我不只是自己从字典中选择键并尝试围绕一个条目构建它给定并保存在变量中。

【问题讨论】:

  • 感谢您的评论,我已经用完整的代码编辑了帖子

标签: python list dictionary object indexing


【解决方案1】:

您需要将del positions[place] 替换为positions.remove(place) 才能删除"A3"

或者您可以使用以下索引直接删除它: self.__dictionary['battleship'].remove(shot_pose)

输出与您预期的相同。

【讨论】:

    【解决方案2】:

    类型

    职位

    是列表。所以发生错误是因为

    删除位置[地点]

    我的答案是

    __dictionary = {'battleship': ['A1', 'A2', 'A3', 'A4']}
    shot_pose = "A3"
    for positions in __dictionary.values():
        if shot_pose in positions:
            positions.remove(shot_pose)
    print(__dictionary)
    

    【讨论】:

    • 非常感谢您的支持!把它修好了:))!
    【解决方案3】:

    我不知道这是否是你要找的,但你去吧:

    a = {'battleship': ['A1', 'A2', 'A3', 'A4']}
    
    shot_pose = "A3"
    
    a['battleship'].remove(shot_pose)
    
    print(a)
    

    如果不是,请给出完整的代码和预期的输出。

    【讨论】:

    • 你为什么要回答一些你自己不确定他们要求的东西?
    • 也许是因为他的问题根本不清楚?
    • 给我造成的不便,我深表歉意,我想把问题写得简单而集中,可能会更有帮助,但这里是现在完整编写的代码
    • @Joel 很抱歉试图帮助人们而不知道他们真正想要什么,因为他们没有正确地提出问题
    猜你喜欢
    • 2016-03-14
    • 2012-02-21
    • 1970-01-01
    • 2016-03-13
    • 2023-01-07
    • 1970-01-01
    • 2017-01-22
    • 1970-01-01
    相关资源
    最近更新 更多