Comparing a matrix (list[][]) ?

Scott David Daniels scott.daniels at acm.org
Sun Jan 14 00:16:12 EST 2007


bearophileHUGS at lycos.com wrote:
> mat = [[9, 8,  12, 15], ..., [0,  0,  0,  5]]
> 
> print min(el for row in mat for el in row if el > 0)
> ...
> If the OP needs the position he/she can do something like:
    << iterative solution >>

Or you can still use min by keeping the position after the value:

     value, x_pos, y_pos = min( (elem, x, y)
                                for y, row in enumerate(mat)
                                    for x, elem in enumerate(row)
                                        if elem > 0 )

You get the "first" entry with the minimal value.
This code raises ValueError if all entries of mat are <= 0.

--Scott David Daniels
scott.daniels at acm.org



More information about the Python-list mailing list