开发者

Most efficient way to update attribute of one instance

I'm creating an arbitrary number of instances (using for loops and ranges). At some event in the future, I need to change an attribute for only one of the instances. What's the best way to do this?

开发者_如何学编程

Right now, I'm doing the following:

1) Manage the instances in a list.

2) Iterate through the list to find a key value.

3) Once I find the right object within the list (i.e. key value = value I'm looking for), change whatever attribute I need to change.

for Instance within ListofInstances:
    if Instance.KeyValue == SearchValue:
        Instance.AttributeToChange = 10

This feels really inefficient: I'm basically iterating over the entire list of instances, even through I only need to change an attribute in one of them.

Should I be storing the Instance references in a structure more suitable for random access (e.g. dictionary with KeyValue as the dictionary key?) Is a dictionary any more efficient in this case? Should I be using something else?

Thanks,

Mike


Should I be storing the Instance references in a structure more suitable for random access (e.g. dictionary with KeyValue as the dictionary key?)

Yes, if you are mapping from a key to a value (which you are in this case), such that one typically accesses an element via its key, then a dict rather than a list is better.

Is a dictionary any more efficient in this case?

Yes, it is much more efficient. A dictionary takes O(1) on average to lookup an item by its key whereas a list takes O(n) to lookup an item by its key, which is what you are currently doing.

Using a Dictionary

 # Construct the dictionary
 d = {}

 # Insert items into the dictionary
 d[key1] = value1
 d[key2] = value2
 # ...

 # Checking if an item exists
 if key in d:
      # Do something requiring d[key]
      # such as updating an attribute:
      d[key].attr = val


As you mention, you need to keep an auxiliary dictionary with the key value as the key and the instance (or list of instance with that value for their attribute) as the value(s) -- way more efficient. Indeed, there's nothing more efficient than a dictionary for such uses.


It depends on what the other needs of your program are. If all you ever do with these objects is access the one with that particular key value, then sure, a dictionary is perfect. But if you need to preserve the order of the elements, storing them in a dictionary won't do that. (You could store them in both a dict and a list, or there might be a data structure that provides a compromise between random access and order preservation) Alternatively, if more than one object can have the same key value, then you can't store both of them in a single dict at the same time, at least not directly. (You could have a dict of lists or something)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜