【问题标题】:dictionary decomposition and creating a new dictionary with identical values字典分解并创建具有相同值的新字典
【发布时间】:2018-11-24 22:37:39
【问题描述】:

我有一本字典myDict

{'1': 5, '2': 13, '3': 23, '4': 17}

我正在使用这段代码,它对我很有帮助,以便在 myDict 中找到最接近 targetVal 的键/值

answer = key, value = min(myDict.items(), key=lambda (_, v): abs(v - targetVal))

假设targetVal14answer 返回:

('2': 13)

我现在需要做的是处理myDict 中的相同值。例如,如果 myDict 现在是:

{'1': 5, '2': 13, '3': 23, '4': 13}

我需要值13 的这两个键/值对。 如果代码(上面)在myDict 中找到最接近的值,并且该值恰好出现不止一次,我想创建一个新字典。在这种情况下,answer 将返回:

{'2': 13, '4': 13}

是否可以更新发现answer 的方式以解决最接近的值出现多次的情况?

【问题讨论】:

  • {k:v for k,v in myDict.items() if v == answer[1]}
  • dict 对于这类任务来说不是一个好的数据结构。
  • 我会列出一个元组列表,但我最近一直在使用字典,所以我更愿意操作它们
  • @Chris_Rands,answer 不只是 1 个键/值吗?
  • 您没有尝试我的解决方案吗? answer[1] 是值,它有效

标签: python python-2.7 dictionary python-2.x


【解决方案1】:

先找到最小值,然后过滤你的dict

>>> d = {'1': 5, '2': 13, '3': 23, '4': 13}
>>> target = 13
>>> min_ = min(d.itervalues(), key=lambda v: abs(v - target))
>>> {k:v for k,v in d.iteritems() if v == min_}
{'2': 13, '4': 13}

【讨论】:

    【解决方案2】:

    如您所见,min 仅提供满足最低条件的一项。您可以通过手动循环构建一次性解决方案:

    from math import inf
    
    myDict = {'1': 5, '2': 13, '3': 23, '4': 13}
    targetVal = 14
    
    res = {}
    diff = inf
    for k, v in myDict.iteritems():
        current_diff = abs(v - targetVal)
        if current_diff <= diff:
            if current_diff < diff:
                diff = current_diff
                res.clear()
            res.update({k: v})
    
    print(res)
    
    # {'2': 13, '4': 13}
    

    【讨论】:

    • float('inf') 也应该没问题,以防您不想从 math 导入。
    • @timgeb,谢谢,学习新东西!当然,它们是等价的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-25
    • 1970-01-01
    相关资源
    最近更新 更多