如何获取其值至少包含另一个列表中的一个项目的字典键?

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}

现在我需要找到字典中至少有一个列表项的所有键值

示例:Joey 的值是 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),以避免稍后在您的代码中使内置函数无法使用。

不要使用名称listlist是库函数的名称。

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 将在 "sees" 成为共享值后立即停止遍历 v,从而节省一些时间。

您还可以使用集合交集来检查字典值元组中的任何元素是否与您的 "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)]