Python字典平等问题

时间:2013-07-14 19:49:15

标签: python set equality

我有这个奇怪的错误

我有这段代码:

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

1 个答案:

答案 0 :(得分: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