locate items in matrix (index of lists of lists)
clp2 at rebertia.com
Fri Mar 20 12:03:29 CET 2009
On Fri, Mar 20, 2009 at 3:50 AM, Alexzive <zasaconsulting at gmail.com> wrote:
> Hello there,
> let's suppose I have the following matrix:
> mat = [[1,2,3], [3,2,4], [7,8,9], [6,2,9]]
> where [.. , .. , ..] are the rows.
> I am interested into getting the "row index" of all the matrix rows
> where a certain number occurs.
> For example for 9 I should get 2 and 3 (starting from 0).
> For 10 I should get an error msg (item not found) and handle it.
> How to get the"row indexes" of found items?
indices = [i for i, row in enumerate(mat) if item in row]
where item is 9, 10, or whatever you're looking for.
If the item is not present in any of the sublists, indices will be empty.
Also, if you're doing lots of matrix work, you might want to look into
using numpy (google it).
I have a blog:
More information about the Python-list