You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中打印字典时如何筛选指定键不输出,适配文本游戏场景?

解决方案

你不需要删除字典中的item键,只需在提取可移动方向时过滤该键即可。dict.keys()返回的是字典视图对象,不支持直接切片操作,你可以用以下两种方式实现需求:

方法1:列表推导式(最简洁)

直接修改possible_moves的赋值逻辑:

# 遍历所有键,仅保留不等于'item'的方向键
possible_moves = [key for key in rooms[current_room].keys() if key != 'item']

方法2:for循环实现(匹配你之前的思路)

如果你偏好显式的循环写法,可以用以下代码:

possible_moves = []
for key in rooms[current_room].keys():
    # 跳过item键,只把方向键加入列表
    if key != 'item':
        possible_moves.append(key)

完整可运行示例

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'}  # 反派角色
}

current_room = 'Laundry Room'
# 过滤掉item键,只保留方向
possible_moves = [key for key in rooms[current_room].keys() if key != 'item']
print('Possible Moves:', *possible_moves)

运行后输出为Possible Moves: North West,已经自动过滤掉了item键。如果后续你需要排除更多非方向的键,可以把要排除的键放到一个集合里,修改判断逻辑为if key not in {'item', 'desc', 'hint'}即可,扩展性更强。

内容的提问来源于stack exchange,提问作者user17108509

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 10:36:03