[Tutor] a code question, but don't know question's name

Kent Johnson kent37 at tds.net
Sun Oct 7 22:17:35 CEST 2007


Happy Deer wrote:

> First, I have experience in Matlab, where I can use "eval". I wonder 
> whether someone knows about it.

Python has an eval() function but it's use is discouraged, there is 
usually a better way. It would help if you would give us more context 
for your problem.

> Second, if I just want to return data[:,1], ...data[:,-1] separately 
> without knowing ahead how many columns data has. What should I do?

I'm assuming data is a numpy or Numeric array though it would help if 
you would confirm that.

In [10]: from numpy import array
In [11]: a = array([[1,2,3],[4,5,6]])

a.shape gives the dimensions; a.shape[1] is the second dimension

In [15]: a.shape
Out[15]: (2, 3)
In [18]: a.shape[1]
Out[18]: 3

You can use a list comprehension to make a list of the columns.
In [19]: [ a[:,i] for i in range(1, a.shape[1])]
Out[19]: [array([2, 5]), array([3, 6])]

Note you asked for data[:,1], ...data[:,-1] which does not include the 
first column.

Kent


More information about the Tutor mailing list