accessing elements in multi-dimensional sequences
Peter Otten
__peter__ at web.de
Fri May 28 07:41:42 EDT 2004
Rodrigo Daunaravicius wrote:
> Is there an elegant way to directly refer the 2nd dimension of a
> multi-dimensional sequence (like the nth character in a list of strings).
[list of strings example]
While your example doesn't work, as Matteo already explained, the Numeric
package provides an intuitive way to refer to the nth dimension of a
matrix:
>>> a = Numeric.reshape(range(9), (3,3))
>>> a
array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
>>> a[:, :-1]
array([[0, 1],
[3, 4],
[6, 7]])
In spite of its name, Numeric is not limited to numbers:
>>> d = ['0891931243\n', '0325443777\n', '0933477028\n', '0699624617\n']
>>> a = Numeric.array(d)
>>> a.tostring()
'0891931243\n0325443777\n0933477028\n0699624617\n'
>>> a[:, :-1].tostring()
'0891931243032544377709334770280699624617'
Note that shorter strings are filled with spaces:
>>> Numeric.array(["123\n", "4\n", "789\n"]).tostring()
'123\n4\n 789\n'
Of course this is overkill for your example use case.
Peter
More information about the Python-list
mailing list