python - 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 对象进行比较时如何完成它的工作。
解决方案
它们并不完全相同。第一种方法是比较整个元组,第二种方法是只比较similarity
元素。第一种方法等价于
closest_method = max(candidates, key=lambda sim: candidates[sim])
candidates.get(x)
相当于candidates[x]
whenx
是字典的键。并且由于max()
对键进行迭代,因此在这种情况下不会出现键不存在的情况(索引引发异常,默认.get()
返回None
)。
如果所有similarity
元素都是唯一的,那么这两种方法之间就没有区别。但是如果有重复similarity
的值,该.get()
方法将比较标题以对它们进行排序。
推荐阅读
- python - python内嵌版本及请求包
- c# - 不同进程访问相同资源时的线程安全
- artificial-intelligence - pddl precondtion 在计划中无法正常工作
- mysql - Mysql AES_ENCRYPT 只显示字节
- android - 如何实现 ConstraintLayout 工具栏
- wso2 - 无法登录 wso2IS 中的 customuserstore 用户
- python-3.x - 加载 model.5 后如何预测机器翻译
- javascript - 多个元素上的同时事件监听器
- google-cloud-platform - Cloud Pub/Sub 中的可见性超时
- c# - 使用具有大量 URL 的多个 Web 视图时,UWP 应用程序挂起