How would i go about making a function to create a certain number of uniquely named variables at runtime, based on initial user input? For instance, user enters dimensions 400 x 400, (x and y), so i would want the function to create 1600 (400 * 400) variables, each to represent every different point on a grid 400 by 400.
2 Answers
What you really want is an array, a list or a tuple of 400*400 points.
So create a class that stores the information you want at each point, and then create a list of size 400*400 of those class objects.
You can do it this way:
width = 400
height = 400
m = [[0]*width for i in range(height)]
And then access points in your field like so:
m[123][105] = 7
To set point (123,105) to 7.
If you want to store more than just a number at each point, create a class like I suggested:
class MyClass:
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
And then create your list of "MyClass" objects like so:
m = [[MyClass(0,0,0) for i in range(400)] for j in range(400)]
5 Comments
array-s from same-named module, and for things that are seriously larger, numpy. It seems that simple integers are stored anyway, not arbitrary objects. E.g. initializer = [0]*width; matrix = [array('i', initializer) for x in range(height)][MyClass(0,0,0)]*400 creates 400 references to the same object. You'll need [[MyClass(0,0,0) for i in range(400)] for j in range(400)].Are you sure you need to create a different variable for each point on the grid? If there are lots of points with default value of say 0, don't create an array with a bunch of 0s. Instead, create an empty dictionary D = {}. Store data as D[(x,y)] = anything. Access your data by D.get((x,y), 0). Where D.get(key, default value) This saves memory.
Btw, 400*400 is not 1600. Rather 160,000