【问题标题】:how to coorelate multiple values in array with certain name in other array如何将数组中的多个值与其他数组中的某个名称相关联
【发布时间】:2019-04-08 18:36:02
【问题描述】:

我正在尝试使用 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])

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

【问题讨论】:

    标签: arrays python-3.x


    【解决方案1】:

    您可以使用 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 个字符串。

    【讨论】:

      【解决方案2】:

      只是一个建议:您可能会退后一步,重新考虑您对数据建模的方式。如果您需要在给定 (x,y) 值的元组的情况下经常查找内容,您可以考虑制作一个以坐标为键的字典,而不是单独的列表。

      例如:

      from collections import defaultdict
      # defaultdict will allow you to set global default when there's nothing at a coord
      
      placesYX = [(50, 100), (90, 200)]
      place_names = ['First Door', 'some creature']
      places = dict(zip(placesYX, place_names))
      # places looks like
      # {(50, 100): 'First Door', (90, 200): 'some creature'}
      
      # now you can lookup directly:
      places[(50, 100)] # first door
      places[(90, 200)] # some creature
      

      如果您可能会查找字典中没有的坐标,您可以使用:

      places.get((0,0), "some default value")
      

      避免按键错误。

      【讨论】:

        猜你喜欢
        • 2018-12-02
        • 2019-04-02
        • 2020-04-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-02-05
        • 1970-01-01
        相关资源
        最近更新 更多