簡體   English   中英

Python 遍歷字典

[英]Python iterating through dictionary

我正在嘗試遍歷字典,但我不確定在循環時如何更新。

我正在嘗試做的事情(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()

這樣做的問題是它在逐個迭代時不會刪除,它首先計算所有術語然后刪除最低的術語。

這會導致不正確的 output:

 [11, 12, 13, 4, 10, 14, 1, 15]

預期 output:

[1, 13, 15, 4, 12, 11, 14, 5]

訂單無關緊要,我想嘗試在此不使用任何庫。

對不起,如果這聽起來讓我對編程很陌生並且我正在嘗試學習如何使用字典和列表。

也許我從你的描述中遺漏了一些東西,但按照你的邏輯,我得到了相同的 output。

我相信你的代碼是錯誤的,在計數后循環 - 但也許在這種情況下它奇怪地不會改變 output。

requests=[1, 13, 15, 1, 3, 4, 2, 12, 10, 4, 1, 15, 15, 11, 14, 7, 10, 9, 14, 5]

freq = {}

for r in requests:
    r = str(r)
    if r in freq:
        freq[r]+=1
        print(f'Hit {r}')
    else:
        freq[r]=1
        print(f'Miss {r}')
    if len(freq.keys()) > 8:
        # Get list of keys that share the lowest frequency
        k = [int(k) for k, v in freq.items() if v == min(freq.values())]
        print(f'Requests sharing the lowest frequency of {min(freq.values())} -> {k}')
        print(f'Dropping lowest request value -> {min(k)}')
        del freq[str(min(k))]
        
print([int(x) for x in freq.keys()])

最終 Output

[1, 13, 15, 4, 12, 10, 11, 14]

您的解釋非常令人困惑,但據我了解,我們有鍵值對和變量的收入,它們保存為字典(哈希圖),如果頻率具有相同的值,您希望保持最高頻率或最高(鍵)。 簡而言之,您只想在每次更新字典時重新創建字典。 讓我們拿你的代碼:

# creates dictionary out of frequencies based on the input list
def simulating_list(req, req_list):
    req_list[req] = 1 if req not in req_list else req_list[req]+1

# 1.takes items of the list and sorts by frequency;
# 2.takes a slice of the list starting from 8th element from the end
# 3.reverses the list(just to look nice, dictionaries nowadays displyed ordered)
# 4.creates new dictionary out of list of lists


def filter_eight(req_list):
    return dict(sorted(req_list.items(), key=lambda x: x[1])[-8:][::-1])


# Your request lists
requests = [1, 13, 15, 1, 3, 4, 2, 12, 10,
            4, 1, 15, 15, 11, 14, 3, 4, 2, 1, 5, 3, 2, 4, 1, 2, 3, 4, 5, 12, 3, 4, 2, 34,  23, 1, 2, 3, 4, 12, 3, 12, 3, 4, 2, 3, 7, 10, 9, 14, 5]
# data base
req_data_base = {}
# generator inside the list will execute
[simulating_list(i, req_data_base) for i in requests]

print(filter_eight(req_data_base))
# Displays dictionary with key = request, value= frequency
# If you want to display it differently its up to you
# {3: 9, 4: 8, 2: 7, 1: 6, 12: 4, 5: 3, 15: 3, 14: 2}
def fun(requests):
    freq={}
    for i in requests:
        if i in freq:
            freq[i]+=1
            print("hit",i)
        else:
            freq[i]=1
            print("miss",i)
        if len(freq)>8:
            to_remove = min(freq,key=lambda k:(freq[k],k))
            print("to remove",to_remove,"from",freq)
            del freq[to_remove]
    return freq

這與 Chris 的相似,但沒有將事物轉換為字符串,另一件事是使用min的鍵 function 獲取要刪除的元素,我們使用該對 (value,key) 作為比較鍵元組是可排序的,並且它們的順序由它們的值 position 基數給出,因此如果它們在第一個 position 中具有相同的值(或在這種情況下為頻率),請檢查其第二個 Z4757FE07FD492A8BE0EA6A760D683要求)

>>> requests=[1, 13, 15, 1, 3, 4, 2, 12, 10, 4, 1, 15, 15, 11, 14, 7, 10, 9, 14, 5]
>>> result=fun(requests)
miss 1
miss 13
miss 15
hit 1
miss 3
miss 4
miss 2
miss 12
miss 10
hit 4
hit 1
hit 15
hit 15
miss 11
to remove 2 from {1: 3, 13: 1, 15: 3, 3: 1, 4: 2, 2: 1, 12: 1, 10: 1, 11: 1}
miss 14
to remove 3 from {1: 3, 13: 1, 15: 3, 3: 1, 4: 2, 12: 1, 10: 1, 11: 1, 14: 1}
miss 7
to remove 7 from {1: 3, 13: 1, 15: 3, 4: 2, 12: 1, 10: 1, 11: 1, 14: 1, 7: 1}
hit 10
miss 9
to remove 9 from {1: 3, 13: 1, 15: 3, 4: 2, 12: 1, 10: 2, 11: 1, 14: 1, 9: 1}
hit 14
miss 5
to remove 5 from {1: 3, 13: 1, 15: 3, 4: 2, 12: 1, 10: 2, 11: 1, 14: 2, 5: 1}
>>> result
{1: 3, 13: 1, 15: 3, 4: 2, 12: 1, 10: 2, 11: 1, 14: 2}
>>> list(result)
[1, 13, 15, 4, 12, 10, 11, 14]
>>> 
        

(另請注意,字典默認迭代其鍵,因此實際上沒有必要調用.keys)

暫無
暫無

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

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