我有两个名单,房间和床位。
rooms = ['r1', 'r2', 'r3', 'r4']
beds = ['b11', 'b12', 'b13', 'b21', 'b22', 'b31', 'b41', 'b42']
我创建了一个字典来跟踪列表中的每个元素(之后我会需要它):
def create_dict():
global clean_rooms
clean_rooms = {}
for room in rooms:
clean_rooms[room] = 0
global clean_beds
clean_beds = {}
for bed in beds:
clean_beds[bed] = 0
我保存了我的词典:
fileName = "rooms list"
fileObject = open(fileName, 'w')
pickle.dump(clean_rooms, fileObject)
fileObject.close()
fileName = "beds list"
fileObject = open(fileName, 'w')
pickle.dump(clean_beds, fileObject)
fileObject.close()
这是我被困的地方。我想创建一个函数来从之前创建的词典中选择一个随机床和一个随机房间,并在字典(房间和床)中为所选键的值添加一个单位。
之后我需要再次使用更新的密钥保存字典,以便在我第二次调用该函数时使用它们,第三次使用它们等等:这是我不完整的函数:
def todo():
fileName = "rooms list"
fileObject =open(fileName, 'r')
clean_rooms = pickle.load(fileObject)
room = random.choice(list(clean_rooms))
clean_rooms[room] += 1
fileName = "beds list"
fileObject =open(fileName, 'r')
clean_beds = pickle.load(fileObject)
bed = random.choice(list(clean_beds))
clean_beds[bed] += 1
fileName = "rooms list"
fileObject = open(fileName, 'w')
pickle.dump(clean_rooms, fileObject)
fileObject.close()
fileName = "beds list"
fileObject = open(fileName, 'w')
pickle.dump(clean_beds, fileObject)
fileObject.close()
解决!我很蠢,我每次都调用函数来创建字典!
答案 0 :(得分:1)
我会完全重新设计这个。首先,创建保存到文件并从文件加载的函数:
def pickle_dict(d, filename):
with open(filename, 'w') as f:
pickle.dump(d, f)
def unpickle_dict(filename):
with open(filename) as f:
return pickle.load(f)
接下来,创建原始空字典的函数:
def create_dict(keys):
d = {}
for key in keys:
d[key] = 0
return d
现在您可以轻松创建原始文件:
rooms = ['r1', 'r2', 'r3', 'r4']
room_file = "room_dict.txt"
pickle_dict(create_dict(rooms), room_file)
并创建随机添加到房间的功能:
def dirty_room(room_file):
rooms = unpickle_dict(room_file)
room = random.choice(list(clean_rooms))
clean_rooms[room] += 1
pickle_dict(clean_rooms, room_file)
您可以为beds
复制所有内容。
注意我没有使用global
- 所需的一切都是函数的显式参数。这使得开发和测试变得更加容易,许多具有明确职责的短期功能也是如此。