Python字典列表中的项

2024-04-29 10:54:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在创建一个战舰游戏,我有一个查找字典,其中舰船和坐标是它们的值,它们都保存在一个主类中的self.\u dict dictionary对象中

{'battleship': ['A1', 'A2', 'A3', 'A4'], 'cruiser': ['E1', 'F1', 'G3'], 'destroyer': ['D5', 'D6'], 'submarine': ['I9']}

当条目不在船舶坐标中时,我的代码应放在板上“*”,当条目在坐标中时,我的代码应放在板上“X”

出于某种原因,代码没有读取值中的快照,而是打印未命中的“*”快照

changin_line变量,是插入到游戏板中的新行,包括标记

x_index变量,是拾取的坐标,参考标记应放置的位置

shot = "A3"
        
if shot not in self.__dict.values():
     changin_line.insert(x_index, "*")   
else:
     changin_line.insert(x_index, "X")

Tags: 代码标记self游戏index字典line条目
1条回答
网友
1楼 · 发布于 2024-04-29 10:54:42

self.__dict.values()是一个列表列表,而不是一个位置列表。因此,您将字符串与列表进行比较,这永远不会是真的

您需要向下钻取另一个级别:

if not any(shot in ship_pos for ship_pos in self.__dict.values()):
    changin_line.insert(x_index, "*")
else:
    changin_line.insert(x_index, "X")

最好是反转数据结构。使用坐标作为关键点,而不是使用船舶类型作为关键点:

{'A1': 'battleship', 'A2': 'battleship', 'A3': 'battleship', 'A4': 'battleship',
 'E1': 'cruiser', 'F1': 'cruiser', 'G1': 'cruiser',
 ...
}

然后您可以测试if shot in self.__dict:。如果你想知道哪艘船被击中,那就简单地说self.__dict[shot]

顺便说一句,__dict对于这个变量来说似乎不是一个好名字。把它叫做ship_positions

相关问题 更多 >