Tuesday, September 15, 2009

[Py] Python: array and list

When I tested some basic functions in iPython, I noticed the differences between array and list.

At the beginning, I thought that if there are two matrices matA and matB in the same dimension, then I can just add their corresponding elements with ``matA + matB.'' By doing some tests, however, I found it's not what I expected.

>>> matA = [[1, 2], [3, 4]]
>>> matA
[[1, 2], [3, 4]]
>>> matB = [[-1, -2], [-3, -4]]
>>> matB
[[-1, -2], [-3, -4]]
>>> matC = matA + matB
>>> matC
[[1, 2], [3, 4], [-1, -2], [-3, -4]]

The plus operator concentrated matA and matB, and this was not what I needed.

Importing the ``array'' module still cannot let me do things I wanted.

>>> import array
>>> matA = array.array("i", [1, 2, 3, 4])
>>> matA
array('i', [1, 2, 3, 4])
>>> matB = array.array("i", [-1, -2, -3, -4])
>>> matC = matA + matB
>>> matC
array('i', [1, 2, 3, 4, -1, -2, -3, -4])

The solution is ``to use SciPy.'' Yes, if you want to manipulate matrices with Python more intuitively, remember to import scipy.

>>> from scipy import *
>>> from pylab import *
>>> matA = array([[1, 2], [3, 4]])
>>> matA
array([[1, 2],
[3, 4]])
>>> matB = array([[-1, -2], [-3, -4]])
>>> matB
array([[-1, -2],
[-3, -4]])
>>> matC = matA + matB
>>> matC
array([[0, 0],
[0, 0]])

No comments:

Post a Comment