首页 > 解决方案 > 如何将数组中的多个值与其他数组中的某个名称进行关联

问题描述

我正在尝试使用 cmd 在 python 中制作一个全文本 RPG 游戏,但我需要找到一种将地牢放置在某些 X 和 Y 上的方法。

我尝试创建两个不同的数组:

placesYX = [[50, 100]]
places = ['First Door']

然后制作一个每次都会检查的功能

if x == placesYX[0][0] and y == placesYX[0][1]:
        print('you are at: ', places[0])

但我不能对我添加的每个地方都重复这个,我需要一个函数来检查 x 和 y 是否都匹配 placesXY 中的任何值,如果它是真的:

print('You are at: ', places[mathcingplace])

感谢任何回答的人(我是初学者)

标签: arrayspython-3.x

解决方案


您可以使用 python 的枚举功能来跟踪您的位置的索引和值:

placesXY = [[50, 100], [75, 150]]
places = ['First Door', 'Second Door']

def check_place(x, y):
    for index, coordinates in enumerate(placesXY):
        if coordinates[0] == x and coordinates[0] == y:
            return f"You are at: {places[index]}"

enumerate让您跟踪列表中的索引以及列表中的值。

f"some string {variable}"让您(f)格式化带有变量的字符串,并且可以打印 f 个字符串。


推荐阅读