arrays - 如何将数组中的多个值与其他数组中的某个名称进行关联
问题描述
我正在尝试使用 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])
感谢任何回答的人(我是初学者)
解决方案
您可以使用 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 个字符串。
推荐阅读
- sql - SQLite 内存数据库不会关闭
- html - 有没有办法将 Windows 经典树视图添加到网页?
- python - Numpy 继承;向 Numpy 数组添加方法
- statsmodels - statsmodels ARIMA 预测没有外生变量的未来值
- azure - 如何将单个应用服务计划中的 Azure 应用服务分配给虚拟网络中的不同子网
- php - 口音显示正确的一半时间
- authentication - 在flutter中通过rest api登录验证用户
- javascript - Microsoft Websocket 代码示例返回错误
- discord.js - Discord.JS 阻止一个人写消息
- python - 如何通过 Selenium 查找动态 ID 的元素