Brian van den Broek wrote:
2) To get around that, and be more efficient with matricies with many empty cells:
.>>> my_matrix_as_dict = {(1,1):4, (1,2):6, (1,3):8,
(2,1):56, (2,3):12,
(3,1):3, (3,2):3}


.>>> my_matrix_as_dict[(3,1)]
3
.>>> my_matrix_as_dict[(2,1)]
56

So, you just can use the tuple co-ordinates you've defined in order to access cells. Note also that the list way you'd have to represent empty cells with a standard null value -- None is the usual choice. But this way, you just don't define some tuples as keys, as I didn't define (2,2) as a key. Thus:

.>>> my_matrix_as_dict[(2,2)]

Traceback (most recent call last):
  File "<pyshell#19>", line 1, in -toplevel-
    my_matrix_as_dict[(2,2)]
KeyError: (2, 2)

You can make that more graceful with a try/except block:

.>>> try:
my_matrix_as_dict[(2,2)]
except KeyError:
print "That cell is empty"
That cell is empty
.>>>



if you want None to be returned for an empty cell, you can just do:

my_matrix_as_dict.get((2,2), None)

so that  the None object will de returned for all inexistant cells...

Hugo
_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to