在Python中对元组进行哈希运算,顺序在哪里起作用?

在Python中对元组进行哈希运算,顺序在哪里起作用?,python,Python,我有: 然而,元组1和元组2都得到相同的计数。什么是散列一组2个事物的方法,以便顺序很重要?散列时考虑顺序: tuple1 = token1, token2 tuple2 = token2, token1 for tuple in [tuple1, tuple2]: if tuple in dict: dict[tuple] += 1 else: dict[tuple] = 1 这假设对象本身具有唯一的散列。即使它们没有,在字典中使用它时也可以(

我有:


然而,元组1和元组2都得到相同的计数。什么是散列一组2个事物的方法,以便顺序很重要?

散列时考虑顺序:

tuple1 = token1, token2
tuple2 = token2, token1
for tuple in [tuple1, tuple2]:
    if tuple in dict:
        dict[tuple] += 1
    else:
        dict[tuple] = 1
这假设对象本身具有唯一的散列。即使它们没有,在字典中使用它时也可以(只要对象本身不等于它们的
\uuuuu eq\uuu
方法定义的值):


请注意,由于哈希冲突,此dict的效率可能低于没有哈希冲突的另一个dict:)

它们获得相同计数的原因是您的代码同时显式增加
token1、token2和
token2、token1
计数。如果不这样做,计数将不会保持同步:

>>> t1 = 'a',hash('a') 
>>> [hash(x) for x in t1]  #both elements in the tuple have same hash value since `int` hash to themselves in cpython
[-468864544, -468864544]
>>> t2 = hash('a'),'a'
>>> hash(t1)
1486610051
>>> hash(t2)
1486610051
>>> d = {t1:1,t2:2}  #This is OK.  dict's don't fail when there is a hash collision
>>> d
{('a', -468864544): 1, (-468864544, 'a'): 2}
>>> d[t1]+=7
>>> d[t1]
8
>>> d[t1]+=7
>>> d[t1]
15
>>> d[t2]   #didn't touch d[t2] as expected.
2

看起来您已经发布了循环体的一个实例。我是否可以建议您将其用于您正试图做的事情,这正是您想要做的,但有一行:

In [16]: import collections

In [17]: d = collections.defaultdict(int)

In [18]: d[1,2] += 1

In [19]: d[1,2]
Out[19]: 1

In [20]: d[2,1]
Out[20]: 0

我想我通常会把它写成
d[(1,2)]
,而不是
d[1,2]
,即使它们是等价的……当然,假设
token1
token2
散列()
是不同的值,但我认为值得一提的是,当您有一个包含该类实例的元组时,您可以在类上重写
\uuuuu hash\uuuu
,从而使顺序不相关。。。但即便如此,取决于
\uuuu eq\uuuu
的实现方式,您的
dict
仍然可以正常运行(尽管由于哈希冲突,效率非常低)。@sr2222--由于您的评论,我进一步更新了我的答案。这对我来说很有趣,我想你可能会觉得很有趣。这很有趣。我需要重读dicts内部工作的文档…@sr2222——当我观看我转发的视频时,我学到了很多
In [16]: import collections

In [17]: d = collections.defaultdict(int)

In [18]: d[1,2] += 1

In [19]: d[1,2]
Out[19]: 1

In [20]: d[2,1]
Out[20]: 0
counter = (collections.Counter(myListOfTuples) + 
           collections.Counter([j,i for i,j in myListOfTuples]))