我正在尝试遍历一个字典,但我不确定在遍历时如何更新
我想做的(Simulating LFU cache)
:
收到请求后,
逐个遍历每个请求,并计算每个请求使用字典的频率
如果字典包含超过8个键,请删除频率最低的值,如果这些值的频率都相等,则删除字典中的最低键
因此,从当前8中删除最低的键,并将第9个键放入其中
然后继续这样做,直到剩下8个值
目前我有:
requests=[1, 13, 15, 1, 3, 4, 2, 12, 10, 4, 1, 15, 15, 11, 14, 7, 10, 9, 14, 5]
lst=[] #only holds 8 ints
def leastFrequent():
#user inputs requests manually
print (requests)
freq = {} #Dictionary
for i in requests:
if i in freq.keys():
#Increase frequency by 1
freq[i] += 1
print("Hit", i)
else:
#If not set frequency to 1
freq[i] = 1
print("Miss", i)
#I want to move my while loop inside this i think?? but i get errors with it being a dictionary
freq = sorted(freq.items(), key=lambda k: k[0])#places dictionary into list of lists
freq.sort(key=lambda x: x[1])#sort in order
print("Converted frequency:",str(freq))
while len(freq)>8:
print("Size greater than 8..\n",str(freq[0]))
del freq[0]#atm this just deletes the first value printed since it should be the lowest
if len(freq)<=8:
break
#i then move elements[0] into a final list to be printed
lst=[item[0] for item in freq]
print ("\nPrinting final list")
print(lst)
leastFrequent()
问题是它在逐个迭代时不会删除,而是先计算所有项,然后删除最低的项
这会导致不正确的输出:
[11, 12, 13, 4, 10, 14, 1, 15]
预期产出:
[1, 13, 15, 4, 12, 11, 14, 5]
订单不重要,我想尝试在这方面不使用图书馆
抱歉,如果这听起来让人困惑,我是编程新手,我正在学习如何使用字典和列表
你的解释很混乱,但据我所知,我们有键:值对和变量的收入,它们被保存为字典(哈希映射),如果频率有相同的值,你希望保持最高频率或最高(键)。简而言之,我的建议是,你只想在每次更新字典时重新创建它。让我们看看您的代码:
这与Chris的类似,但没有将东西转换为字符串,另一件事是使用
min
的键函数获取要删除它的元素,我们使用元组是可排序的,并且它们的顺序由它们的值位置基给出,因此如果它们具有相同的值,则使用对(值,键)作为比较键(或本例中的频率)在第一个位置,检查其第二个位置,即我们的字典键(或给定的请求)(还请注意,字典对其键进行迭代是默认的,因此实际上不需要调用.keys)
也许我在你的描述中遗漏了什么,但是按照你的逻辑,我得到了相同的输出
我相信您的代码是错误的,在计数后循环-但在这种情况下,它可能奇怪地没有改变输出
最终产量
相关问题 更多 >
编程相关推荐