locate items in matrix (index of lists of lists)

Tino Wildenhain tino at wildenhain.de
Fri Mar 20 07:07:38 EDT 2009


Alexzive 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?
> 
> In practice I am looking for an equivalent to "list.index(x)" for the
> case "lists of lists"

Actually you are not ;) list.index(x) gives you the index of the
first occurence of the item.

So what you seem to want is a list of indexes to the lists where
your item is contained.

Something like:

x=9

[idx for idx,row in enumerate(mat) if x in row]

should do.

> 
> 
> PS: this is just a simplified example, but I have actually to deal
> with large matrices [~500000 * 4]

This is something I'd consider either reordering your data (for example
into dictionary) or look at scipy/numpy.

Regards
Tino
-------------- next part --------------
A non-text attachment was scrubbed...
Name: smime.p7s
Type: application/x-pkcs7-signature
Size: 3241 bytes
Desc: S/MIME Cryptographic Signature
URL: <http://mail.python.org/pipermail/python-list/attachments/20090320/86513d7a/attachment-0001.bin>


More information about the Python-list mailing list