gpt4 book ai didi

python - 在 Python 中散列一个元组,其中顺序很重要?

转载 作者:行者123 更新时间:2023-12-03 09:44:16 25 4
gpt4 key购买 nike

我有:

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 件事,以便顺序很重要?

最佳答案

散列时考虑顺序:

>>> hash((1,2))
1299869600
>>> hash((2,1))
1499606158

这假设对象本身具有唯一的哈希值。即使他们不这样做,在字典中使用它时仍然可以(只要对象本身不等于其 __eq__ 方法定义的):
>>> 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

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

关于python - 在 Python 中散列一个元组,其中顺序很重要?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14388306/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com