我写了一个简单的脚本,其范围是:
list=[1,19,46,28 etc...]
dictionary={Joey:(10,2,6,19), Emily: (0,3), etc}
现在我需要查找字典中所有值中至少有一个列表条目的键
示例:19是Joeys值,因此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")
但这非常耗时,因为它基本上遍历数据库中的所有内容。我可以请求帮助优化这个吗?谢谢!
答案 0 :(得分:5)
我会使用列表理解和内置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)]
小心不要将builtins指定为对象的名称(例如list
),以避免以后在代码中使内置函数无法使用。
答案 1 :(得分:2)
请勿使用名称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
看到"后立即停止迭代require
。共享价值,节省一些时间。
答案 2 :(得分:1)
您还可以使用set intersection来检查字典值元组中的任何元素是否与您的“list”条目有任何共同点:
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)]