【问题标题】:comparing multiple values assigned to one key in two dictionaries比较分配给两个字典中一个键的多个值
【发布时间】:2018-12-19 10:08:36
【问题描述】:

我正在尝试比较两个字典。每个字典都有一个键和分配给该键的 2 个值。每个字典可能有不同的长度。

我希望编写一个循环,首先检查两个字典中的键是否匹配。然后检查第一个字典中的第一个和第二个值是否在第二个字典中的第一个和第二个值之间。

示例字典:

gas_dict ={{'methane': (85, 98), 'ethane': (1, 12), 'propane': (0.1, 6)...x}

scope_dict ={'methane': (35, 100), 'ethane': (0.05, 15), 'propane': (1, 11)...n}

其中 x 和 y

我的部分代码成功检查了键是否匹配:

for key in scope_dict.keys():
            if key in gas_dict.keys():

但是,我一直在试图弄清楚如何比较 2 个键的 4 个值。

【问题讨论】:

标签: python dictionary


【解决方案1】:
def range_subset(range1, range2):
    return (range1[0]>=range2[0] and range1[1]<=range2[1])

for key in dict1.keys():
    if key in dict2.keys():
        print(key)
        print(range_subset(dict1[key], dict2[key]))
        print('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~')

【讨论】:

  • 变量名是垃圾,但我相信你可以在你的代码中创建适合你的有意义的函数/变量名。
【解决方案2】:

我认为这是解决您问题的方法:

def gas_in_scope(gas_dict, scope_dict):
    # For each gas
    for k, (g1, g2) in gas_dict.items():
        # Get scope values
        if k not in scope_dict:
            return False
        s1, s2 = scope_dict[k]
        # Check gas values are within the scope
        if not (s1 <= g1 <= s2 and s1 <= g2 <= s2):
            return False
    # If all values are fine then return true
    return True

print(gas_in_scope({'methane': (85,  98), 'ethane': (   1, 12)},
                   {'methane': (35, 100), 'ethane': (0.05, 15)}))
# True

print(gas_in_scope({'methane': (85,  98), 'ethane': (   1, 12), 'propane': (0.1,  6)},
                   {'methane': (35, 100), 'ethane': (0.05, 15), 'propane': (  1, 11)}))
# False

【讨论】:

  • 抱歉,我忘了说 scope_dict 可能比 gas_dict 包含更多的键和值。我将编辑我的问题。
  • 您的答案有效,但当 scope_dict 中有更多键时返回 false。因此,不会执行此 if 语句之后的剩余代码。
  • 这样的scope_dict 是在哪里定义的?显示给定输入的假设和预期结果
  • 我已经修改了我原来的问题以明确这一点。
  • @Joey 我明白了,谢谢你的澄清,我更新了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多