【问题标题】:Python: Comparing two dictionaries to see if two separate values matchPython:比较两个字典以查看两个单独的值是否匹配
【发布时间】:2020-02-27 18:31:38
【问题描述】:

我有两个字典数组,我试图检查其中两个值是否与另一个字典的值完全匹配,在每个值上,然后仅返回该值的值,并且只返回一次.我尝试的方法返回的结果比原始数组大得多。下面是一个例子。

first = [{“num1”: 1, “num2”: 2}, {“num1”: 1, “num2”: 3}, {“num1”: 1, “num2”: 4}, {“num1”: 2, “num2”: 5}]

second = [{“num1”: 1, “num2”: 7, “num3”: 10}, {“num1”: 1, “num2”: 3, “num3”: 8}, {“num1”: 3, “num2”: 4, “num3”: 5}, {“num1”: 1, “num2”: 2, “num3”: 5}, {“num1”: 2, “num2”: 5, “num3”: 11}, {“num1”: 1, “num2”: 8, “num3”: 9}]

这就是数组的样子。我要检查的是第二个数组的值是否匹配第一个数组的两个条目,无论位置如何,然后将第二个数组中的整个条目添加到一个新数组中。因此,运行后,将创建一个新数组,其中包含来自第二个数组的第 2、第 4 和第 5 个条目。

我尝试的是这样的:

for item in first:
    for entry in second:
        if item[“num1”] == entry[“num1”]:
            if item[“num2”] == entry[“num2”]:
                new_array.insert(len(new_array), entry)
            if item[“num2”] == entry[“num3”]:
                new_array.insert(len(new_array), entry)
        if item[“num1”] == entry[“num2”]:
            if item[“num2”] == entry[“num3”]:
                new_array.insert(len(new_array), entry)

但是,当我运行它时,我得到了一个庞大的数组,比原始数组大得多。然后我删除了所有重复的值,发现它和原来的第二个字典一样大小,所以它只是不加选择地复制了每个条目。

我做错了什么?

【问题讨论】:

  • 我在手机上输入了这个,但代码不起作用。
  • 我刚刚提交了一个清理代码的推荐编辑

标签: python arrays dictionary compare


【解决方案1】:

希望我没听错。这是解决方案。

    first = [
    {"num1": 1, "num2": 2}, 
    {"num1": 1, "num2": 3}, 
    {"num1": 1, "num2": 4}, 
    {"num1": 2, "num2": 5}
]

second = [
    {"num1": 1, "num2": 7, "num3": 10},
    {"num1": 1, "num2": 3, "num3": 8},
    {"num1": 3, "num2": 4, "num3": 5},
    {"num1": 1, "num2": 2, "num3": 5},
    {"num1": 2, "num2": 5, "num3": 11}, 
    {"num1": 1, "num2": 8, "num3": 9}
]


for s in second:
    s = list(s.values())
    for f in first:
        f = list(f.values())
        if f[0] in s and f[1] in s:
            print(s)

代码将检查第二个字典中的两个值是否也出现在第一个字典中。

【讨论】:

  • 这会检查两个值都存在还是只存在一个?
  • 我明白了问题的重点。稍后我将编辑我的代码。
  • 另外,有没有办法检查条目不包含两者?
  • 我修改了代码,执行后你会得到想要的结果。可以通过添加“else”语句来检查条目是否不包含两者。
  • 嗯,开始和结束数组的大小还是一样的,而且运行时间要长。
猜你喜欢
  • 2018-05-14
  • 2015-08-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-14
  • 2017-09-04
相关资源
最近更新 更多