【发布时间】: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