python - 如何显示字典中的项目列表?
问题描述
问题要求通过定义一个名为print_room_items(room)
I 的函数,我应该将一个房间作为输入并显示在这个房间中找到的项目列表。如果房间内没有物品,则不打印任何内容。
这是其中的2个房间:
room_reception = {
"name": "Reception",
"description": '768',
"exits": {"south": "Admins", "east": "Tutor", "west": "Parking"},
"items": [item_biscuits, item_handbook]
}
room_tutor = {
"name": "your personal tutor's office",
"description": '890',
"exits": {"west": "Reception"},
"items": []
}
我想出的代码是:
def print_room_items(room):
room_item_01 = room['items'][0]['name']
room_item_02 = room['items'][1]['name']
print(room_item_01)
print(room_item_02)
print_room_items(rooms["Reception"])
这样的代码看起来不是特别优雅。最重要的是,当我尝试为没有任何项目而不是没有输出的房间运行代码时,我确实遇到了错误。在这种情况下,导师室。
解决方案
一种方法:
def print_room_items(room):
for item in room ['items']:
print(item)
或者,如果您需要打印的是“item ['name']”:
def print_room_items(room):
for item in room ['items']:
print(item['name'])
推荐阅读
- vhdl - VHDL-2008 分层信号访问阵列
- c# - 假设它是整数,将浮点整数作为字段添加到 InfluxData.Net 会引发异常
- c++ - while()中调用了lambda表达式,为什么要在lambda表达式后面加()
- regex - 如何在 Vim 中修剪匹配的字符?
- java - 使用 LIKE 关键字从 Java 中的 oracle 数据库中搜索
- actionscript-3 - 无法从正常大小切换视频
- python - 重定向时 /upload/ 处的 NoReverseMatch
- c - C - 调用函数并给出二维数组
- c - 如何在 C 中的字符串内设置变量占位符
- c++ - 模板 ID 不匹配任何模板声明