![](/img/trans.png)
[英]How to extract the corresponding key whose value contains the item from a list?
[英]How to get dictionary key whose value contains at least one item in another list?
我寫了一個簡單的腳本,其范圍是:
list=[1,19,46,28 etc...]
dictionary={Joey:(10,2,6,19), Emily: (0,3), etc}
現在,我需要查找字典中所有在鍵中至少有一個列表項的鍵。
示例:在Joeys值中為19,所以Joey是贏家。
我是怎么做到的:(完全沒有程序員)
# NodesOfSet = the list
# elementsAndTheirNodes = the dictionary
# loop as many times as the number of key:value entries in the dictionary element:nodes
# simply: loop over all the elements
for i in range (0, len (elementsAndTheirNodes.keys())):
# there is an indent here (otherwise it wouldnt work anyway)
# loop over the tuple that serves as the value for each key for a given i-th key:value
# simply: loop over all their nodes
for j in range (0, len (elementsAndTheirNodes.values()[i])):
# test: this prints out element + 1 node and so on
# print (elementsAndTheirNodes.keys()[i], elementsAndTheirNodes.values()[i][j] )
for k in range (0, len (NodesOfSet)):
if NodesOfSet[k] == (elementsAndTheirNodes.values()[i][j]):
print ( elementsAndTheirNodes.keys()[i], " is the victim")
else:
print ( elementsAndTheirNodes.keys()[i], " is not the victim")
但這非常耗時,因為它基本上遍歷數據庫中的所有內容。 我可以尋求幫助來優化這一點嗎? 謝謝!
我會用一個列表理解和內建的any
一次共享的項目被發現了地短路。 將您的列表變成一組可以將成員資格查找的復雜度從O(n)
到O(1)
:
s = set(lst)
result = [k for k, v in dct.items() if any(i in s for i in v)]
注意不要將內建函數指定為對象的名稱(例如list
),以免在以后的代碼中使內建函數不可用。
不要使用名稱list
, list
是庫函數的名稱。
l = [1, 19, 46, 28, ...]
l_set = set(l)
d = {'Joey':(10,2,6,19), 'Emily': (0,3), ...}
winners = [k for k, v in d.items() if any(i in l_set for i in v)]
只要“看到”共享值, any
都將停止遍歷v
,從而節省了一些時間。
您還可以使用集合交集來檢查字典值元組中的任何元素是否與“列表”條目有任何共同點:
l = [1,19,46,28, ...]
s = set(l)
d = {Joey:(10,2,6,19), Emily: (0,3), ...}
winners = [k for k, v in d.iteritems() if s.intersection(v)]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.