我被学校项目所困扰。以下函数应该在给定的字典中设置房间的名称。房间dicionary应该保留,因为使用它的函数。它应该随机设置rom的名称,以便稍后在另一个函数中显示它。
import string
import random
names = ['This', 'happens', 'all', 'the', 'time']
for key, value in rooms.items():
# do something with value
rooms[value]["name"] = random.choice(names)
names.remove(rooms[value]["name"])
room_1 = {"name" : "",
"description" : """ """,
"exits" : {"east": "Second" , "south":"Fourth"},
"items" : []}
room_2 = {"name": "",
"description" : """ """,
"exits" : {"west": "First" , "south":"Fifth" , "east":"Third"},
"items" : []}
rooms = {"First" : room_1,
"Second" : room_2,}
答案 0 :(得分:1)
要使您发布的脚本有效,您需要:
将for
lop移动到脚本的末尾(设置值后)
rooms
)。它在rooms
变量上运行,必须对其进行定义
冷杉
修复for
循环。如果要修改字典的值,请使用rooms[key]
访问它,而不是rooms['value']
。
`这样的事情:
import random
names = ['This', 'happens', 'all', 'the', 'time']
rooms = {
"First": {},
"Second": {},
}
for key in rooms:
# do something with value
name = random.choice(names)
rooms[key]["name"] = name
names.remove(name)