【问题标题】:Is there a way of adding an item to a dictionary within an if statement with python?有没有办法在使用 python 的 if 语句中将项目添加到字典中?
【发布时间】:2019-01-09 17:55:22
【问题描述】:

我正在制作一个基于文本的冒险游戏,并尝试根据玩家在其库存中拥有一个密钥来将项目添加到目录中。

我已经尝试了所有我能找到的解决方案,但都没有奏效。我想这可能是因为我的语法与其他词典不同。

    if 'key' in inventory:
    print('Well done for killing all monsters on the first floor! You can 
    now 
    travel upstairs from the hall')
    'Hall' ['upstairs'] = 'Landing'

     'Hall' : {
              'south' : 'Kitchen',
              'east'  : 'Dining Room',
              'north' : 'Library',
              'west' : 'Game Room',
            }, 

请告诉我另一种方式

    'Hall' ['upstairs'] = 'Landing'

无需更改所有目录,因为我还有许多其他房间。

【问题讨论】:

  • 什么是'Hall'的类型?
  • Um 'Hall' ['upstairs'] = 'Landing' 正在尝试将基于索引的赋值用于 字符串'Hall' 与另一个字符串作为键。
  • @junapa.arrivillaga:这只是之前不起作用的解决方案之一。

标签: python python-3.x dictionary if-statement game-development


【解决方案1】:

您提到了我不熟悉的“不同语法”-所以我想这实际上是您出现问题的地方。请参阅下面的改编 - 这是您预期的行为吗?

Hall = {
    'south': 'Kitchen',
    'east': 'Dining Room',
    'north': 'Library',
    'west': 'Game Room',
}

inventory = ['key']

if 'key' in inventory:
    print('Well done for killing all monsters on the first floor! You can now travel upstairs from the hall')
    Hall['upstairs'] = 'Landing'

print(Hall)
# Output: {'south': 'Kitchen', 'east': 'Dining Room', 'north': 'Library', 'west': 'Game Room', 'upstairs': 'Landing'}

注意:您需要先定义您的字典Hall,然后才能分配像Hall['upstairs'] = 'Landing' 这样的键值对。

【讨论】:

  • 感谢您的回答,但我尝试删除引号,但没有成功。
  • 究竟是什么没用?你试过运行我的代码吗?
  • 我在测试以前的可能解决方案时尝试了完全相同的方法。不过感谢您的帮助。
  • 那么解决了吗?或者您现在遇到哪个问题/错误? (感谢您接受我的回答)
  • 好的,很好,不用担心 - 只是想确保 - 玩得开心(如果它是公开的,至少在完成后在 cmets 中看到一个链接会很高兴)我确实这么认为)。
猜你喜欢
  • 1970-01-01
  • 2020-12-29
  • 1970-01-01
  • 2014-12-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-27
  • 2021-03-26
相关资源
最近更新 更多