最近,我为我的同事创建了一个猜谜游戏,作为学习Python3.3x的一个项目。我将结果存储在一个用名称和分数格式化的文本文件中,用冒号分隔,如.
Adam:12
Dave:25
Jack:13
Adam:34
Dave:23由于Padraic Cunningham,文本文件是用下面的代码读取的。
from collections import defaultdict
d = defaultdict(list)
with open('guesses.txt') as f:
for line in f:
name,val = line.split(":")
d[name].append(int(val))
for k in sorted(d):
print(k," ".join(map(str,d[k])))现在的问题是,我想看看戴夫,亚当和杰克最近的四分。我想到这一点的一种方法是以某种方式阅读上面的列表并将其反转,这样它就会首先看到最新的结果。我想我可以首先用下面的代码来反演字典:
inv_map = {v: k for k, v in d.items()}但这不起作用,因为它返回错误:
TypeError: unhashable type: 'list'由于我想存储4个最近的结果,那么我需要确保每次新结果到达时删除最老的结果,并更新字典。
如何确保每个键只分配4个最大值?那能通过倒字典来实现吗?我曾尝试看看其他问题是否符合同样的原则,但我并没有发现任何问题。
注意到我已经看到了itemgetter方法,但是每个键有多个值。
文本文件将如下所示:
Adam:12
Dave:25
Jack:13
Adam:34
Dave:23
Jack:17
Adam:28
Adam:23
Dave:23
Jack:11
Adam:39
Dave:44
Jack:78
Dave:38
Jack:4 发布于 2015-02-08 08:19:33
您可以使用defaultdict和deque(maxlen=4)来处理这个问题。
import collections
d = collections.defaultdict(lambda: collections.deque(maxlen=4))
# defaultdict accepts as an argument a function that returns the default
# state of the value of undefined keys. In this case we make an anonymous
# function that returns a `collections.deque` with maxlen of 4.
# we could also do
# # import functools, collections
# # d = collections.defaultdict(functools.partial(collections.deque,
# # maxlen=4))
with open('path/to/file.txt', 'r') as infile:
for line in infile:
player,score = line.strip().split(":")
d[player].append(int(score))但是,您最好先创建这个数据结构,然后对对象进行筛选。
import pickle
# `highscores` is some previously populated high score dict
def save_scores(filename):
with open(filename, 'w') as outfile:
pickle.dump(highscores, outfile)
def load_scores(filename):
with open(filename, 'r') as infile:
highscores = pickle.load(infile)
return highscoreshttps://stackoverflow.com/questions/28391928
复制相似问题