Search code examples
pythonlistmatlablist-comprehension

Python List indexed by tuples


I'm a Matlab user needing to use Python for some things, I would really appreciate it if someone can help me out with Python syntax:

(1) Is it true that lists can be indexed by tuples in Python? If so, how do I do this? For example, I would like to use that to represent a matrix of data.

(2) Assuming I can use a list indexed by tuples, say, data[(row,col)], how do I remove an entire column? I know in Matlab, I can do something like

 new_data = [data(:,1:x-1) data(:,x+1:end)];

if I wanted to remove column x from data.

(3) How can I easily count the number of non-negative elements in each row. For example, in Matlab, I can do something like this:

 sum(data>=0,1)

this would give me a column vector that represents the number of non-negative entries in each row.

Thanks a lot!


Solution

  • I agree with everyone. Use Numpy/Scipy. But here are specific answers to your questions.

    1. Yes. And the index can either be a built-in list or a Numpy array. Suppose x = scipy.array([10, 11, 12, 13]) and y = scipy.array([0, 2]). Then x[[0, 2]] and x[y] both return the same thing.

    2. new_data = scipy.delete(data, x, axis=0)

    3. (data>=0).sum(axis=1)

    Careful: Example 2 illustrates a common pitfall with Numpy/Scipy. As shown in Example 3, the axis property is usually set to 0 to operate along the first dimension of an array, 1 to operate along the second dimension, and so on. But some commands like delete actually reverse the order of dimensions as shown in Example 2. You know, row major vs. column major.