如何仅在字典中存储一个键的3个值?蟒蛇 [英] How to only store 3 values for a key in a dictionary? Python
问题描述
所以我试图只允许程序只存储每个键(名称)的最后3个分数(值),但是我遇到一个问题,程序只存储3个分数,然后不更新最后3个或程序附加
So I tried to only allow the program to store only last 3 scores(values) for each key(name) however I experienced a problem of the program only storing the 3 scores and then not updating the last 3 or the program appending more values then it should do.
我到目前为止的代码:
#appends values if a key already exists
while tries < 3:
d.setdefault(name, []).append(scores)
tries = tries + 1
推荐答案
虽然我不能完全理解你的问题,但我从中得出的概念是,你只想在列表中存储最后三个分数。这是一个简单的任务。
Though I could not fully understand your question, the concept that I derive from it is that, you want to store only the last three scores in the list. That is a simple task.
d.setdefault(name,[]).append(scores)
if len(d[name])>3:
del d[name][0]
该代码将检查列表的长度是否超过3。如果超过,则删除第一个元素(在最后三个元素之前添加的元素)
This code will check if the length of the list exceeds 3 for every addition. If it exceeds, then the first element (Which is added before the last three elements) is deleted
这篇关于如何仅在字典中存储一个键的3个值?蟒蛇的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!