[英]Compare keys in a list of dictionaries
我想比较两个字典列表。 第一个字典具有键“对”和“概率”。 这个字典按'prob'排序。 然后将第一列表的顶部x量项与具有键“对”和“距离”的第二列表进行比较。 我只是比较,看看第一个列表中的“对”是否在第二个列表中。 如果发现我需要记录找到的那个匹配。 输出是匹配的数量
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对。我想将列表中的每个元素与我需要的范围(前十位,前五位和上半位)进行比较,然后迭代通过元素在清单2中。但我不知道列表1和列表2之间的大小是否重要,我不知道如何比较键值“对”
你的问题并不完全清楚。 例如,您正在获取第一个列表的前1/10,1 / 5和1/2,但是您没有指定要从哪个比率中获取匹配数。 无论如何,这是一些可以帮助您解决问题的代码。 如果您提供更多信息,我会编辑它。
def analyze(expected,actual):
sorted_list = sorted(expected, key=lambda k: k['prob'],reverse=True)
toptenth = sorted_list[:int(len(sorted_list)/10)]
topfifth = sorted_list[:int(len(sorted_list)/5)]
tophalf = sorted_list[:int(len(sorted_list)/2)]
actual_pairs = [el["pairs"] for el in actual]
matching_tenth = len([el for el in toptenth if el["pairs"] in actual_pairs])
matching_fifth = len([el for el in topfifth if el["pairs"] in actual_pairs])
matching_half = len([el for el in tophalf if el["pairs"] in actual_pairs])
return { "tenth": matching_tenth,
"fifth": matching_fifth,
"half": matching_half}
print (analyze(list1, list2))
输出是:
{'tenth': 1, 'fifth': 1, 'half': 3}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.