首页 > 解决方案 > max(dict, dict.get) 当 dict 项是 NamedTuple 对象时

问题描述

我的目标是在字典中找到元素的 id,其中相似性参数最高。

我不确定我是否理解为什么这两种方法的工作方式相同,如果有人能解释一下,我将不胜感激。

这是我的 python 3.6 代码:


class ParentCandidate(NamedTuple):
    similarity: float
    title: str


c1 = ParentCandidate(0.875, 'longest title 1')
c2 = ParentCandidate(1, 'title 2')
c3 = ParentCandidate(0.9, 'title 3')
c4 = ParentCandidate(1.1, 'title 4')
c5 = ParentCandidate(0.5, 'title 5')

candidates = {1: c1, 2: c2, 3: c3, 4: c4, 5: c5}

closest_method1 = max(candidates, key=candidates.get)
closest_method2 = max(candidates, key=lambda sim: candidates[sim].similarity)
print(closest_method1, closest_method2)
assert closest_method1 == closest_method2

第二种方法完全按计划工作,我们如何识别最大相似度值似乎很清楚,因为我们直接引用它。虽然我根本不明白 max() 函数在接收 NamedTuple 对象进行比较时如何完成它的工作。

标签: pythondictionarymaxnamedtuple

解决方案


它们并不完全相同。第一种方法是比较整个元组,第二种方法是只比较similarity元素。第一种方法等价于

closest_method = max(candidates, key=lambda sim: candidates[sim])

candidates.get(x)相当于candidates[x]whenx是字典的键。并且由于max()对键进行迭代,因此在这种情况下不会出现键不存在的情况(索引引发异常,默认.get()返回None)。

如果所有similarity元素都是唯一的,那么这两种方法之间就没有区别。但是如果有重复similarity的值,该.get()方法将比较标题以对它们进行排序。


推荐阅读