[Tutor] simple array access
Edwin Boyette
edwin_boyette at yahoo.com
Thu Jan 8 08:30:48 CET 2009
--- On Wed, 1/7/09, Artie Ziff <artie.ziff at gmail.com> wrote:
From: Artie Ziff <artie.ziff at gmail.com>
Subject: [Tutor] simple array access
To: Tutor at python.org
Date: Wednesday, January 7, 2009, 9:12 PM
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
## There are probably much easier, elegant ways to populate a list
## This is fast enough to generate to express the idea
## There is a row/col method also but I haven't used it
## List comprehensions may be prettier/faster (check Kent's page I believe he has
## write up on them
some_sequence = []
i = 0
k = []
for i in range (10):
k.append(i)
for i in range (10):
some_sequence.append(k)
for stuff in some_sequence:
print stuff
print "Some sequence has 10 outer indexes beginning at [0] and ending at [9]"
print "The first element of index [0] is the value 0, and can be accessed at some_sequence[0][0] :" + str(some_sequence[0][0])
print "The last element of index [9] ## the 10th line or index is the value 9, and can be accessed at some_sequence[9][9] :" + str(some_sequence[9][9])
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20090107/0a241e25/attachment.htm>
More information about the Tutor
mailing list