Skip to main content
 首页 » 编程设计

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

2025年05月04日10duanxz

我写了一个简单的脚本,其范围是:

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