【问题标题】:Compare keys in a list of dictionaries比较字典列表中的键
【发布时间】: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


【解决方案1】:

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

【讨论】:

  • 抱歉含糊不清。我最终需要计算每个比率的匹配数;但是,我只需要前十分之一的比例就可以让我开始画画,其余的我自己完成
  • 这应该可以。考虑到您可能需要“选择”元素的值,我编写了代码。如果您只需要匹配的数量并且您正在处理大型列表,请记住代码可以进行很多优化。
猜你喜欢
  • 2022-11-21
  • 2019-12-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-21
  • 2021-11-13
  • 1970-01-01
  • 2017-06-21
相关资源
最近更新 更多