[Tutor] Matrix

Rob Kapteyn 12345671 at comcast.net
Mon Dec 20 04:44:03 CET 2004


Hello to the list !

A list of lists is the most logical construction.
But -- you don't need to assemble the rows separately --
this works too:
 >>> my_matrix_as_lists = [ [4, 6, 8, 1],\
... 					  [2, 5, 1, 3],\
...					  [2, 1, 2, 8] ]

 >>> print my_matrix_as_lists[1][1]
5

Rob

On Dec 19, 2004, at 1:31 PM, Brian van den Broek wrote:

> Bugra Cakir said unto the world upon 2004-12-19 10:33:
>> hi,
>> I want to create a matrix in Python. For example 3x4 how can i
>> create this? thanks
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> http://mail.python.org/mailman/listinfo/tutor
>
> Hi,
>
> at least two ways using only builtins occur to me:
>
> 1) A list of lists:
>
> .>>> row1 = [4, 6, 8, 1]
> .>>> row2 = [2, 5, 1, 3]
> .>>> row3 = [2, 1, 2, 8]
> .>>> my_matrix_as_lists = [row1, row2, row3]
> .>>> print my_matrix_as_lists[1][1]
> 5
>
> Note that
> >>> row1[1]
> 6
>
> since indicies start at 0.
>
> 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
> .>>>
>
> HTH,
>
> Brian vdB
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>



More information about the Tutor mailing list