【问题标题】:unpacking Tuples in dict在dict中解包元组
【发布时间】:2018-02-05 03:39:00
【问题描述】:

所以我正在制作一个游戏,我有一个元组字典,其中包含运动场上对象的坐标,如下所示(例如):

location = {player : (1, 4), monster : (3, 2), escape : (4, 0)}

稍后在我的代码中,我想将坐标更改为更易于理解的区域。第一个定义部分是一个对应的字母,然后是第二个数字,看起来像这样:玩家在 B4,怪物在 C2,依此类推。右上角的“区域”由元组 (4, 4) 表示,左下角的“区域”由元组 (0, 0) 表示。我唯一能想到的可能是这样的:

location = {player : (1, 4), monster : (3, 2), escape : (4, 0)}
letters = ["A", "B", "C", "D", "E"]
playerArea = "{}{}".format(letters[int(location[player[0]])+1], location[player[1]])

简而言之,它没有用。我认为问题在于从字典中解包元组并将其用作从列表字母中获取字母的数字。对不起,这是令人困惑的,我会尽力回答你所有的问题。

【问题讨论】:

  • 什么是player
  • 另外,您能否举一个您期望的输出示例?目前还不清楚。
  • 不清楚:A 应该是 1 还是 0
  • player 是一个元组,元组包含 2 个 int 和 x 和 y 值。因为玩家移动,整数在不断变化
  • 另外,您的语法不正确。要访问播放器元组的第一个元素,您需要使用location['player'][0] 而不是location['player'[0]]。这同样适用于dict 中的其他元素。

标签: python dictionary tuples


【解决方案1】:

问题的核心是如何将数字行/列坐标转换为更易读的东西(战舰风格)。这是一个简单而快速的函数:

>>> def rc_to_abc(x, y):
        return 'ABCDEFGHIJKLOMOPQRSTUVWXYZ'[x] + str(y)

>>> rc_to_abc(1, 4)
'B4'
>>> rc_to_abc(3, 2)
'D2'
>>> rc_to_abc(4, 0)
'E0'

【讨论】:

  • chr(65+x) 而不是'ABCDEFGHIJKLOMOPQRSTUVWXYZ'[x] - 但这不能很好地处理无效输入。 IndexError 可能比意外字符更好。
  • 更好:import string; def rc_to_abc(x, y): return string.ascii_uppercase[x] + str(y)
【解决方案2】:

使用 字典理解 使用字符串格式来构建新值。解压值元组很容易:

location = {k: '{}{}'.format(letters[x-1], y) for k, (x, y) in location.items()}
print(location)
# {'player': 'A4', 'monster': 'C2', 'escape': 'D0'}

另外,您可以使用string.ascii_uppercase 而不是手动定义字母列表。

OTOH,因为你的董事会应该有一个 (0, 0) 不确定你打算做什么索引 0 因为 A 已经被视为 1

【讨论】:

    【解决方案3】:

    您可以使用string.ascii_uppercase 获取用于每个坐标的完整字母列表:

    from string import ascii_uppercase as alphabet
    
    location = {"player":(1, 4), "monster":(3, 2), "escape":(4, 0)}
    
    new_location = {a:alphabet[b[0]-1]+str(b[-1]) for a, b in location.items()}
    
    print(new_location)
    

    输出:

    {'player': 'A4', 'monster': 'C2', 'escape': 'D0'}
    

    【讨论】:

      猜你喜欢
      • 2020-09-17
      • 2021-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-16
      • 2010-10-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多