简体   繁体   English

如何只为字典中的键存储3个值? 蟒蛇

[英]How to only store 3 values for a key in a dictionary? Python

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. 所以我试着只允许程序只存储每个键(名称)的最后3个分数(值)但是我遇到的问题是程序只存储3个分数然后不更新最后3个或程序附加更多值然后它应该做。

The code I have so far: 我到目前为止的代码:

    #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]

This code will check if the length of the list exceeds 3 for every addition. 此代码将检查每次添加时列表的长度是否超过3。 If it exceeds, then the first element (Which is added before the last three elements) is deleted 如果超过,则删除第一个元素(在最后三个元素之前添加)

Use a collections.defaultdict + collections.deque with a max length set to 3: 使用collections.defaultdict + collections.deque ,最大长度设置为3:

from collections import deque,defaultdict

d = defaultdict(lambda: deque(maxlen=3))

Then d[name].append(score) , if the key does not exist the key/value will be created, if it does exist we will just append. 然后d[name].append(score) ,如果该键不存在,将创建键/值,如果它确实存在,我们将只追加。

deleting an element from the start of a list is an inefficient solution. 从列表的开头删除元素是一种低效的解决方案。

Demo: 演示:

from random import randint

for _ in range(10):
    for name in range(4):
            d[name].append(randint(1,10))

print(d)
defaultdict(<function <lambda> at 0x7f06432906a8>, {0: deque([9, 1, 1], maxlen=3), 1: deque([5, 5, 8], maxlen=3), 2: deque([5, 1, 3], maxlen=3), 3: deque([10, 6, 10], maxlen=3)})

One good way for keeping the last N items in python is using deque with maxlen N, so in this case you can use defaultdict and deque functions from collections module. 保留python中最后N个项的一个好方法是使用带有maxlen N的deque ,因此在这种情况下,您可以使用collections模块中的defaultdictdeque函数。

example : 例如:

>>> from collections import defaultdict ,deque
>>> l=[1,2,3,4,5]
>>> d=defaultdict()
>>> d['q']=deque(maxlen=3)
>>> for i in l:
...    d['q'].append(i)
... 
>>> d
defaultdict(<type 'collections.deque'>, {'q': deque([3, 4, 5], maxlen=3)})
from collections import defaultdict  
d = defaultdict(lambda:[])
d[key].append(val)
d[key] = d[key][:3]


len(d[key])>2 or d[key].append(value) # one string solution

A slight variation on another answer in case you want to extend the list in the entry name 如果要扩展条目name的列表,请稍微改变另一个答案

d.setdefault(name,[]).extend(scores)
if len(d[name])>3:
    del d[name][:-3]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM