【发布时间】:2020-12-05 03:01:04
【问题描述】:
我正在尝试遍历字典,但我不确定在循环时如何更新。
我正在尝试做的事情(Simulating LFU cache):
请求被接受,
逐个遍历每个请求,并统计每个使用字典的频率。
如果字典包含超过 8 个键,则删除频率最低的值,如果值的频率都相等,则删除字典中的 LOWEST 键。
因此删除当前 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]
顺序无关紧要,我想尝试不使用任何库。
对不起,如果我对编程很陌生并且我正在尝试学习如何使用字典和列表,这听起来很令人困惑。
【问题讨论】:
标签: python