0

我有这个奇怪的错误

我有这段代码:

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 以某种方式输入了“实例”而不是整数。
感谢您的评论!

4

1 回答 1

0

打印 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
于 2013-07-14T20:55:59.763 回答