[英]Dictionary with lists as values - find longest list
我有一本字典,其中的值是列表。 在刪除重復項后,我需要找到哪個鍵的列表最長作為值。 如果我只是找到最長的列表,這將不起作用,因為可能有很多重復項。 我已經嘗試了幾件事,但沒有什么是正確的。
d = # your dictionary of lists
max_key = max(d, key= lambda x: len(set(d[x])))
# here's the short version. I'll explain....
max( # the function that grabs the biggest value
d, # this is the dictionary, it iterates through and grabs each key...
key = # this overrides the default behavior of max
lambda x: # defines a lambda to handle new behavior for max
len( # the length of...
set( # the set containing (sets have no duplicates)
d[x] # the list defined by key `x`
)
)
)
由於max
的代碼遍歷字典的鍵(這是字典遍歷的內容,by. for x in dict: print x
將打印dict
每個鍵)它將返回它找到的具有最高結果的鍵當它應用我們為key=
構建的函數(這就是lambda
所做的)時。 你可以在這里做任何事情,這就是它的美妙之處。 但是,如果您想要鍵和值,則可以執行以下操作....
d = # your dictionary
max_key, max_value = max(d.items(), key = lambda k,v: len(set(v)))
# THIS DOESN'T WORK, SEE MY NOTE AT BOTTOM
這是不同的,因為我們沒有傳遞d
,這是一個字典,而是傳遞d.items()
,它是一個由d
的鍵和值構建的元組列表。 例如:
d = {"foo":"bar", "spam":['green','eggs','and','ham']}
print(d.items())
# [ ("foo", "bar"),
# ("spam", ["green","eggs","and","ham"])]
我們不再看字典了,但所有數據都還在! 使用我使用的解包語句可以更輕松地處理: max_key, max_value =
。 這與您執行WIDTH, HEIGHT = 1024, 768
。 max
仍然像往常一樣工作,它遍歷我們用d.items()
構建的新列表,並將這些值傳遞給它的key
函數( lambda k,v: len(set(v))
)。 您還會注意到我們不必執行len(set(d[k]))
而是直接在v
上操作,這是因為d.items()
已經創建了d[k]
值,並且使用了lambda k,v
使用相同的解包語句將鍵分配給k
並將值分配給v
。
魔法! 顯然不起作用的魔法。 我在這里沒有深入挖掘,實際上lambda
s 不能自行解壓縮值。 相反,請執行以下操作:
max_key, max_value = max(d.items(), key = lambda x: len(set(x[1])))
對於不太高級的用戶,這可以是一個解決方案:
longest = max(len(item) for item in your_dict.values())
result = [item for item in your_dict.values() if len(item) == longest]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.