【发布时间】:2017-09-18 16:36:03
【问题描述】:
我写了一个简单的脚本,其范围是:
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")
但这非常耗时,因为它基本上会迭代数据库中的所有内容。我可以寻求帮助来优化这个吗?谢谢!
【问题讨论】:
-
只是一个提示:这不是很pythonic -> 列表是一个受保护的单词,所以不要将它用作变量名,变量总是以小写字母开头,“单词”通常是用“_”隔开。也不要在函数和“()”之间放置空格,如 print 或 len 或 range
-
您好!谢谢你的评论。我不知道在任何地方使用列表这个词。带有大写字母的东西很有趣,尽管不是很有帮助。空格在那里是因为我的文本编辑器在输入时向我提供了已经使用过的单词。
-
很高兴有人编辑了我的问题以使其更易于理解。但是真的有必要删除我不是程序员吗?谢谢?
标签: python list dictionary key-value