【发布时间】:2019-04-08 13:40:45
【问题描述】:
我正在尝试比较两个字典列表。第一个字典有键“pairs”和“prob”。该字典按“概率”反向排序。然后将第一个列表的前 x 数量项与具有键“pairs”和“distance”的第二个列表进行比较。我只是比较第一个列表中的“对”是否在第二个列表中。如果找到它,我需要记录找到的匹配项。输出是匹配的数量
from operator import itemgetter
list1 = [
{"pairs": (1, 107), "prob": .78},
{"pairs": (1, 110), "prob": .98},
{"pairs": (1, 111), "prob": .74},
{"pairs": (1, 114), "prob": .42},
{"pairs": (1, 74), "prob": .24},
{"pairs": (1, 75), "prob": .25},
{"pairs": (10, 24), "prob": .61},
{"pairs": (10, 28), "prob": .40},
{"pairs": (10, 77), "prob": .42},
{"pairs": (10, 78), "prob": .60}]
list2 = [
{"pairs": (1, 100), "distance": 7.507},
{"pairs": (1, 110), "distance": 6.981},
{"pairs": (1, 111), "distance": 6.741},
{"pairs": (1, 114), "distance": 7.432},
{"pairs": (1, 7), "distance": 5.247},
{"pairs": (1, 75), "distance": 7.254},
{"pairs": (11, 24), "distance": 7.611},
{"pairs": (11, 20), "distance": 6.407},
{"pairs": (10, 77), "distance": 6.422},
{"pairs": (10, 78), "distance": 6.607}]
def analyze(expected,actual):
matches = 0
sorted_list = sorted(expected,key=lambda k: k['prob'],reverse=True)
toptenth = len(sorted_list)/10
topfifth = len(sorted_list)/5
tophalf = len(sorted_list)/2
for i in range(toptenth):
if expected[i]..........
print matches
我不确定如何将列表 1 中的前几个元素与列表 2 的对进行比较。我想将列表 1 中的每个元素与我需要的范围(前 10 名、前 5 名和上半部)进行比较,然后遍历列表 2 中的元素。但我不知道列表 1 和列表 2 之间的不同大小是否重要,我不知道如何仅比较键值“对”
【问题讨论】:
-
你说
I am only comparing to see if the "pairs" from the first list are in the second list.,但第一个列表中的所有对都在第二个列表中。我不明白。 -
这是一个虚拟列表。第二个列表可以有不同的对。给出的实际列表可以有更多的元素,并且可以有不同的对。
-
我更改了列表 2 以进行澄清。
-
请告诉我们您的预期结果。谢谢。
标签: python list dictionary compare key