Jew*_*ile 1 python dictionary list key-value
我写了一个简单的脚本,其范围是:
list=[1,19,46,28 etc...]
dictionary={Joey:(10,2,6,19), Emily: (0,3), etc}
Run Code Online (Sandbox Code Playgroud)
现在我需要找到字典中所有值中至少有一个列表条目的键
示例: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")
Run Code Online (Sandbox Code Playgroud)
但这非常耗时,因为它基本上遍历数据库中的所有内容.我可以请求帮助优化这个吗?谢谢!
我会使用列表理解和内置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)]
Run Code Online (Sandbox Code Playgroud)
注意不要将builtins指定为对象的名称(例如list),以避免以后在代码中使内置函数无法使用.
| 归档时间: |
|
| 查看次数: |
98 次 |
| 最近记录: |