比较字典列表中的键

2024-09-30 18:16:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试着比较两本词典。第一个字典有“pairs”和“prob”键。这本词典是按“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之间大小的差异是否重要,我也不知道如何比较键值“pairs”


Tags: from元素列表数量len字典listdistance
1条回答
网友
1楼 · 发布于 2024-09-30 18:16:31

你的问题不太清楚。例如,您正在获取第一个列表的前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}

相关问题 更多 >