[英]delete item from a list value in dictionary Python
我正在嘗試從在字典中設置為值的列表中刪除一個項目,該字典是一個自我 object 看起來像這樣
{'battleship': ['A1', 'A2', 'A3', 'A4']}
我有一個與給定元素一起保存的變量,要從列表中刪除:
shot_pose = "A3"
預期 output:
{'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()
稍后在創建程序的 rest 時,這個鏡頭 position 將是用戶輸入的條目,這就是為什么我不只是 select 將由我自己提供的一個條目圍繞字典構建保存在變量中。
類型
職位
是列表。 所以發生錯誤是因為
刪除位置[地點]
我的回答是
__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)
您需要將del positions[place]
替換為positions.remove(place)
才能刪除"A3"
或者您可以使用以下索引直接刪除它: self.__dictionary['battleship'].remove(shot_pose)
輸出與您預期的相同。
我不知道這是否是您要找的,但在這里您是 go:
a = {'battleship': ['A1', 'A2', 'A3', 'A4']}
shot_pose = "A3"
a['battleship'].remove(shot_pose)
print(a)
如果不是,請給出完整的代碼和預期的 output。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.