470,872 Members | 1,736 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 470,872 developers. It's quick & easy.

2d Array of (Individual) Objects in Python 2.7.3

2
Hi,

I would like to create a 2d array of objects ex. 50 by 40 cells containing a Tile object each, but I can't figure out how to declare this structure. Built-in array structure doesn't seem to be able to contain custom data, but I might be wrong.

I'd really appreciate if someone could help me out!

Thanks,
AClap
Dec 31 '12 #1

✓ answered by bvdet

If you are familiar with Python classes, it is straightforward to setup a custom array.

A very basic example:
Expand|Select|Wrap|Line Numbers
  1. class Array(object):
  2.     def __init__(self, rows, cols):
  3.         self.rows = rows
  4.         self.cols = cols
  5.         # initialize array and fill with zeroes
  6.         self.data = [[0 for _ in range(cols)] for _ in range(rows)]
  7.     def __iter__(self):
  8.         for row in self.data:
  9.             yield row
  10.     def __repr__(self):
  11.         return 'Array(%d, %d)' % (self.rows, self.cols)
What do you mean by "Tile object"?

2 4164
bvdet
2,851 Expert Mod 2GB
If you are familiar with Python classes, it is straightforward to setup a custom array.

A very basic example:
Expand|Select|Wrap|Line Numbers
  1. class Array(object):
  2.     def __init__(self, rows, cols):
  3.         self.rows = rows
  4.         self.cols = cols
  5.         # initialize array and fill with zeroes
  6.         self.data = [[0 for _ in range(cols)] for _ in range(rows)]
  7.     def __iter__(self):
  8.         for row in self.data:
  9.             yield row
  10.     def __repr__(self):
  11.         return 'Array(%d, %d)' % (self.rows, self.cols)
What do you mean by "Tile object"?
Dec 31 '12 #2
AClap
2
By Tile object I mean instances of the Tile Class, through I'll have to take the time to understand your code, it does work the way I wanted it to. Thank You.
Jan 2 '13 #3

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

2 posts views Thread by jerrygarciuh | last post: by
1 post views Thread by Stormslayer | last post: by
5 posts views Thread by Frederick Gotham | last post: by
2 posts views Thread by wlevine | last post: by
3 posts views Thread by John Devlon | last post: by
3 posts views Thread by sk.rasheedfarhan | last post: by
15 posts views Thread by timothytoe | last post: by
3 posts views Thread by Chris | last post: by
4 posts views Thread by Peskov Dmitry | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.