在Python中使用顺序重要的元组?
发布时间:2020-12-20 13:05:55 所属栏目:Python 来源:网络整理
导读:我有: tuple1 = token1,token2tuple2 = token2,token1for 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 但是,元组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效率低:) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |