【问题标题】:Python dictionary Equality IssuePython字典平等问题
【发布时间】:2026-02-05 02:30:01
【问题描述】:

我遇到了这个奇怪的错误

我有这段代码:

for prev_cand in self.candidates: #loop over a list of dicts
  if prev_cand == cand:
    print "I think these are equal!"
    print prev_cand, cand                                                   
    print "and here are their IDs!"                                         
    print id(prev_cand), id(cand)                                           
    print "and here are their string equalities!"                           
    print str(prev_cand) == str(cand)

产生了以下结果:

I think these are equal!
{'H__0': 2} {'H__0': 1}
and here are their IDs!
27990448 27954960
and here are their string equalities!
False

发生了什么事?我目前正在使用一种仅使用字符串相等的解决方法,但这不是正确的做事方式

我在他们的信息中添加了更多打印:

and keys
['H__0'] ['H__0']
and type of keys
[<type 'str'>] [<type 'str'>]
and values
[2] [1]
and type of values
[<type 'instance'>] [<type 'instance'>]

我正在尝试制作一个可重现的小代码,但到目前为止我还做不到。不过我会继续努力的。 我正在运行 python 2.7.3

好的,所以我认为问题在于 2 和 1 以某种方式输入了“实例”而不是整数。
谢谢大家的评论!

【问题讨论】:

  • 我认为self.candidates 是一本字典是否正确?如果是,您正在比较密钥。
  • @l19:这似乎不太可能,因为 prev_cand 似乎是一本字典。
  • 输出表明对象相等。两者的键和值的类型是什么?字符串键,整数值?那么你所描述的就不可能发生。在任何情况下,SSCCE 都会很有用。
  • 运行{'H__0': 2} == {'H__0': 1} 给出预期的False。您的问题显然缺少一些信息。
  • 是否可以自己提供这两个对象以便重现问题?我猜如果你以prev_cand = {'H__0': 2}cand = {'H__0': 1} 开始代码,这个问题将无法重现。

标签: python set equality


【解决方案1】:

打印 1 和 2 的类的实例(因为 repr)是相同的实例,因此它是相等的。基本上你可以有这样的东西:

class Test:
count = 0
def __init__(self):
    self.a = ["1","2"]
def __repr__(self):
    b = self.a[self.__class__.count]
    self.__class__.count += 1
    return b

>>> a = Test()
>>> b = a
>>> a == b
True
>>> print a, b
1 2

【讨论】: