I am trying to compare two lists of dictionary. The first dictionary has keys "pairs" and "prob". This dictionary is reversed sorted by 'prob'. The top x-amount items of the first list is then compared to the second list which has keys "pairs" and "distance". I am only comparing to see if the "pairs" from the first list are in the second list. If it is found I need to keep record of that match found. the output is the number of matches
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
I am unsure how to compare the top number of elements in list one to the pairs of list 2. I figured taking each element in list one with the range I need (top tenth, top fifth, and top half), then iterating through element in list 2. But I dont know if the varying size between list 1 and list 2 matters and I dont know how to just compare the key value "pairs"
答案 0 :(得分:0)
Your question isn't entirely clear. For example, you are taking the top 1/10, 1/5 and 1/2 of the first list but you don't specify from which ratio you want to take the number of matches. Anyway, This is some code that could help you to solve your problem. I'll edit it if you provide more informations.
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))
Output is:
{'tenth': 1, 'fifth': 1, 'half': 3}