Best way of storing objects to have fast access?

时间:2019-03-19 15:12:51

标签: python

OK, I try one more time, sorry if I was unclear it was my first attempt to ask here something.

# I have such class
# p1 is immutable and uniq. It's using for search
# p2 is mutable parameter
class SomeHashableObject():
    def __init__(self, p1)
        self.p1 = p1
        self.p2 = []

    def __hash__(self):
        return hash(self.p1)

    def __eq__(self, other):
        return self.p1==other.p1

For example I have 2 different of SomeHashableObject.

#Creating and saving
obj_1 = SomeHashableObject(1)
obj_1.p2 = ['a', 'b']
obj_2 = SomeHashableObject(4)
obj_2.p2 = ['c', 'd']

Now I'm want to store my objects and then find one where p1=4

First Way to store and find (list)

# Storing
obj_list = [obj_1, obj_2]
# Searching
result = next(obj for obj in obj_list if obj.p1==4)

Second Way to store and find (hashtable)

# Storing
obj_dict = {
    obj_1: obj_1,
    obj_2: obj_2
}
# Searching
obj_to_search = SomeHashableObject(4)
result = obj_dict[obj_to_search]

Is it the second way acceptable(or better)? I hope now everything is clear)

0 个答案:

没有答案