簡體   English   中英

在Python字典中使每個鍵最多存儲5個值

[英]Making each key store a maximum of 5 values in Python Dictionary


我最近一直在為我的同事創建一個猜謎游戲,作為學習Python 3.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])))

現在的問題是,我想看看Dave,Adam和Jack的最新四個成績。 我想到的一種方法是以某種方式閱讀上面的列表並反轉它,以便它首先看到最新的結果。 我以為可以先使用以下代碼行對字典進行逆運算:

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    

您可以將defaultdictdeque(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 highscores

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM