Python set the variable, hash, how to determine a set of repeated elements

Before always said dictionary key, a set of required elements are immutable objects, in fact, the feeling is not accurate, more accurate to say that the requirements are hashed object. This may also explain the class instance is variable, but can be used as key elements of the set or dictionary.

The official also said the document is a set of hash value unique object of an unordered collection.

https://docs.python.org/3.8/library/stdtypes.html#set-types-set-frozenset 

set object is an unordered collection of distinct hashable objects. Common uses include membership testing, removing duplicates from a sequence, and computing mathematical operations such as intersection, union, difference, and symmetric difference. (For other containers see the built-in dictlist, and tuple classes, and the collections module.)

 Therefore, the collection is determined whether the hash value is repeated by the determination element, not by the memory address. With dictionary key is the same.

I write a verification code:

class SetHash():
    def __init__(self,value):
        self.value = value
    def __eq__(self, other):
        return self.value == other.value
    def __hash__(self):
        #用value计算hash
        return hash(self.value)
hash_set=set()

s1=SetHash('hash')
s2=SetHash('hash')
print("s1 is s2:{}".format(s1 is s2))
print("s1 == s2:{}".format(s1 == s2))
print("s1地址:{}".format(id(s1)))
print("s2地址:{}".format(id(s2)))
#只在集合中添加s1
hash_set.add(s1)
#然后判断s2是否在集合中
print("s2在集合中hash_set:{}".format(s2 in hash_set))

Output:

IS S2 S1: False
S1 S2 ==: True
S1 Address: 4372952344
S2 Address: 4374306544
S2 in the collection hash_set: True

Examples apparent s1 and s2 is not an object, because of the different address, but only added to the empty set s1 in hash_set, also present in the collection hash_set s2, as s1 and s2 of the same hash value, the hash value they the self.value are calculated.

But if we rewrite __hash__ method id (self) or they do not achieve __hash__ __eq__ and methods, the default class is calculated according to the method __hash__ address value. It will not in the set s2 hash_set in.

Modify the code:

class SetHash():
    def __init__(self,value):
        self.value = value
    def __eq__(self, other):
        return self.value == other.value
    def __hash__(self):
        #用id计算hash
        return hash(id(self))

Output:

IS S2 S1: False
S1 S2 ==: True
S1 Address: 4374007536
S2 Address: 4374007368
S2 in the collection hash_set: False

 

Published 115 original articles · won praise 34 · views 90000 +

Guess you like

Origin blog.csdn.net/u011519550/article/details/102884419