问题要求通过定义一个名为 print_room_items(room) 的函数,我应该将一个房间作为输入并显示在该房间中找到的元素列表。如果房间里没有元素,则不会打印任何内容。
这里有两个房间:
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'])
