[Tutor] simple array access

Artie Ziff artie.ziff at gmail.com
Thu Jan 8 03:12:15 CET 2009


Hello,

I used python list comprehension to create a grid (list of lists) of
Objects (instances of MyItem class). Can anyone make recommendations to
achieve a simple access to the elements. My attempt at array access
(like this: array[1,2] ) does not work. What am I overlooking? Thanks in
advance! :)

If anyone has time to show a better way to achieve same, then I am
interested to learn! :)

###

from pprint import *

class MyItem:
  def __init__(self, value):
    self.data=value
  def __repr__(self):
    return 'MyItem(%s)' % (self.data)

class Grid:
  def __init__(self, x, y, value):
    self.data = [[MyItem(float(value))
                  for i in range(x)] for j in range(y)]


if __name__ == "__main__":
  grid = Grid(2, 3, 0.42)
  pprint(grid)
  pprint(grid.data)
  # next line fails to access array element
  pprint (grid.data[1,2])


# EOF #

OUTPUT:

<__main__.Grid instance at 0x7beb8>
[[MyItem(0.42), MyItem(0.42)],
 [MyItem(0.42), MyItem(0.42)],
 [MyItem(0.42), MyItem(0.42)]]
Traceback (most recent call last):
  File "multidim04.py", line 20, in <module>
    pprint (grid.data[1,2])
TypeError: list indices must be integers


Cheers,
Art


More information about the Tutor mailing list