【问题标题】:Is it possible to choose which dictionary keys I want to print in Python?是否可以选择要在 Python 中打印的字典键?
【发布时间】:2021-10-14 18:16:14
【问题描述】:

这是我的第一篇文章,所以请多多包涵。我目前正在上计算机科学入门课程,我们的最后一个项目是制作一个基于文本的游戏,您可以在其中移动一个房间并收集对象。我想为玩家提供他们可能的动作,这样他们就不会浪费时间撞墙。只要玩家选择拿起房间里的物体,我的代码就可以工作。但是,如果他们离开对象,则“项目”会打印在可能的移动中,因为它没有附加。这些是我的想法,但我正在努力将我脑海中的点点滴滴完全联系起来:

if 'item' in rooms[current_room]:
    print(rooms[current_room].keys())  <---- would I add some kind of range here [:]? I'm not sure how I would do that.

也许“for”循环会起作用?类似的东西

for keys in range.....

我不想删除密钥,我只是不想打印它。任何建议将被认真考虑!这是给我带来麻烦的代码:

rooms = {

    'Living Room': {'North': 'Master Bedroom', 'South': 'Kitchen', 'East': 'Laundry Room', 'West': 'Front Porch'},
    'Laundry Room': {'North': 'Back Door', 'West': 'Living Room', 'item': 'Fancy Duds'},
    'Back Door': {'South': 'Laundry Room', 'item': 'Nice Shoes'},
    'Kitchen': {'North': 'Living Room', 'East': 'Your Room', 'item': 'Half-Eaten Box of Chocolates'},
    'Your Room': {'West': 'Kitchen', 'item': 'Cheap Cologne'},
    'Front Porch': {'East': 'Living Room', 'item': 'Freshly Picked Flowers'},
    'Master Bedroom': {'South': 'Living Room', 'East': 'Master Bathroom', 'item': 'Flashlight'},
    'Master Bathroom': {'West': 'Master Bedroom', 'item': 'YOUR MOTHER'}  # villian
}

current_room = 'Laundry Room'

possible_moves = rooms[current_room].keys()

print('Possible Moves:', *possible_moves)

【问题讨论】:

  • 你试图做什么?你说Maybe a 'for' loop 但你没有尝试。首先你可以尝试使用for-loop
  • 当我发布此内容时,我正开始处理 for 循环。老实说,我不确定我能以多快的速度得到对我的问题的答复,所以我在我真正处理我的循环之前发布了。现在我知道这里有一些快速响应者。谢谢!

标签: python dictionary key


【解决方案1】:

你可以这样过滤麻烦的键('item'):

possible_moves = [move for move in rooms[current_room].keys() if move != "item"]
print('Possible Moves:', possible_moves)

这相当于你为它使用for循环的想法,像这样:

possible_moves = []
for move in rooms[current_room].keys():
    if move != 'item':
         possible_moves.append(move)
print(possible_moves)

【讨论】:

  • 谢谢!这是我的大脑试图去的地方,但我的 Python 知识库仍然很小,所以我不知道如何到达那里。谢谢你用两种方式写它,它有助于我理解这个过程。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-05
相关资源
最近更新 更多