<p>您的代码中存在一些问题,这些问题使您无法为您的问题实现一个干净的解决方案。在</p>
<p>首先,我让<code>board_x</code>和<code>board_y</code>实际上包含整数而不是字符串,因为您是在<code>new_village</code>的<code>__init__</code>方法中生成随机整数。在</p>
<pre><code>>>> board_x = list(range(10))
>>> board_y = list(range(1,10))
>>> board_x
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> board_y
[1, 2, 3, 4, 5, 6, 7, 8, 9]
</code></pre>
<p>此外,我会在地图上创建一个列表,列出地图上还没有这样的村庄的所有地点:</p>
^{pr2}$
<p>现在,类代码的关键问题是两个村庄可以在完全相同的位置生成。当发生这种情况并且用户输入坐标时,您如何知道应该打印哪些值?为了防止这种情况,您可以将您的<code>locations</code>传递给<code>__init__</code>方法。在</p>
<pre><code>def __init__(self, locations):
# sanity check: is the board full?
if not locations:
print('board is full!')
raise ValueError
# choose random location on the board as coordinates, then delete it from the global list of locations
self.coordinates = random.choice(locations)
del locations[locations.index(self.coordinates)]
# choose name and tribe
self.name = 'Random name'
self.tribe = random.choice(('gauls', 'teutons'))
</code></pre>
<p>因为您已经为您的村庄创建了一个类,您的列表<code>villages</code>实际上应该包含该类的实例,即</p>
<pre><code>villages = [['5','2'],['5','5'],['8','5']]
</code></pre>
<p>你可以发行</p>
<pre><code>villages = [new_village(locations) for i in range(n)]
</code></pre>
<p>其中<code>n</code>是您想要的村庄数量。
现在,为了便于进一步查找,我建议您创建一个字典,将您板上的位置映射到village实例:</p>
<pre><code>villdict = {vill.coordinates:vill for vill in villages}
</code></pre>
<p>最后,现在很容易处理用户输入并在输入位置打印村庄的值。在</p>
<pre><code>>>> inp = tuple(int(x) for x in input('input x,y: ').split(','))
input x,y: 5,4
>>> inp
(5, 4)
</code></pre>
<p>现在可以发布:</p>
<pre><code>if inp in villdict:
chosen = villdict[inp]
print(chosen.name)
print(chosen.tribe)
else:
print('this spot on the map has no village')
</code></pre>