Home > Blockchain >  How can I efficiently store updateable class objects in Python in a grid?
How can I efficiently store updateable class objects in Python in a grid?

Time:08-17

I have a toy Python project that involves simulating the movement of objects across a grid. My constraints are:

  • The objects are my own arbitrarily defined class(es)
  • The objects can change position on the grid
  • Objects can be added or removed
  • Objects can have their attributes updated
  • I must iterate through all such objects
  • Object's size might be nontrivial (relative to my machine's power)
  • Objects must be able to "see" space taken up on the grid (that is, the grid must be accessible by all objects)

What's the most efficient datatype/container in Python for me to store such objects?


My current thoughts:

  • Numpy array of type object - This seems the best case as I can then reference the objects by their position, but my understanding is numpy isn't really intended for this use case and may not be particularly efficient. Setting it up this way isn't particularly intuitive either.
  • List for the objects and numpy array for shared location updating - This allows a clean iteration through the objects and I could update the location both within class attributes and on the numpy array, but then it's not easy to reference an object specifically by location
  • Dictionary for the objects and numpy array for shared location updating - This would allow me to reference objects by location (keys) and update the master array so knowledge of those changes are shared, but then retaining objects having them move location is odd (they'd need to be copied to new keys I think)

I feel like I may be missing something simple here unless a numpy grid really is the best option.

CodePudding user response:

Summarizing the comments above since no one is posting an answer: Generally speaking, since numpy arrays are designed for numerical computation, there is little benefit in using them for object types compared to a list of lists. This link, however, goes into the nuances of that in more detail. Python then really doesn't have a better option than a list of lists, but this would still accomplish the goal and allow referencing by position. The grid shape could be maintained by initializing it with dummy placeholders and then updating what exists at each position in the list as opposed to outright removing items.

  • Related