python - Python 字典比较 == 如何在幕后工作?
问题描述
我正在使用 == 比较两个字典,如果键和对应的值相似,则返回 true。即使重新排序字典结果也是如此。但我想知道它是如何在幕后发生的。我打印了字典项的 id,发现两个字典中具有相同键或值的所有字典项都具有相同的 id。那么 Python 会比较两个字典中的 id 吗?
dict1 = {'marks': 23}
for key, value in dict1.items():
print(f'Key: {key} with id:{id(key)} :=: value:{value} with id:{id(value)}')
dict2 = {'marks': 23}
for key, value in dict2.items():
print(f'Key: {key} with id:{id(key)} :=: value:{value} with id:{id(value)}')
dict1 == dict2
输出
Key: marks with id:4477545520 :=: value:23 with id:4456492064
Key: marks with id:4477545520 :=: value:23 with id:4456492064
True
这里还有一个问题是如果我打印元组的 id 那么为什么它在每次执行时打印不同的值?
for i in range (1, 11):
for item in dict1.items():
print(f'{i}: item: {item} with id:{id(item)}')
Output:
1: item: ('marks', 23) with id:4546950464
2: item: ('marks', 23) with id:4546764672
3: item: ('marks', 23) with id:4546873984
4: item: ('marks', 23) with id:4547194816
5: item: ('marks', 23) with id:4546711424
6: item: ('marks', 23) with id:4547191680
7: item: ('marks', 23) with id:4546735552
8: item: ('marks', 23) with id:4546929088
9: item: ('marks', 23) with id:4546773696
10: item: ('marks', 23) with id:4546776832
解决方案
需要注意的重要一点是,如果两个变量指向同一个对象,“is”将返回 True。== 如果变量引用的对象相等,则返回 true。
这里参考python的实现:
默认情况下,如果两个字典具有相同的键和值,则它们是相等的。
理解它是如何工作的最好方法是在你自己的类中实现相等。例如:
class MyClass:
def __init__(self, foo, bar):
self.foo = foo
self.bar = bar
def __eq__(self, other):
if not isinstance(other, MyClass):
# don't attempt to compare against unrelated types
return NotImplemented
return self.foo == other.foo and self.bar == other.bar
尝试实现您自己的类的相等性,或查看您感兴趣的其他数据类型如何实现相等性的源代码。
如果它解决了您的问题,请将此答案标记为正确。
推荐阅读
- php - 如何设置自定义路径来浏览和查看它的内容?
- r - imputation 数据框列表:使用调查包或 R 中的 MIcombine 计算分位数?
- c - 数组 c 上的分段错误
- python - 我将如何在 python 3.6 中解析这个 ret
- javascript - 将 JavaScript 数组转换为 formData
- exception - AVIOContext 读取回调中的异常处理
- javascript - 在 JavaScript 中按数组属性分组
- rest - 授权 REST 资源访问
- php - 如何将 php 文件相互交错并检查参数的 URL?
- c++ - C++ 客户端/服务器聊天应用程序 - 从 Ubuntu 命令窗口扫描输入