By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
464,713 Members | 1,503 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 464,713 IT Pros & Developers. It's quick & easy.

2d Array of (Individual) Objects in Python 2.7.3

P: 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"?

Share this Question
Share on Google+
2 Replies

bvdet
Expert Mod 2.5K+
P: 2,851
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

P: 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.