简体   繁体   中英

How to pick the largest number in a matrix of lists in python?

I have a list-of-list-of-lists, where the first two act as a "matrix", where I can access the third list as

list3 = m[x][y]   

and the third list contains a mix of strings and numbers, but each list has the same size & structure. Let's call a specific entry in this list The Number of Interest. This number always has the same index in this list!

What's the fastest way to get the 'coordinates' (x,y) for the list that has the largest Number of Interest in Python?

Thank you!

(So really, I'm trying to pick the largest number in m[x][y][k] where k is fixed, for all x & y, and 'know' what its address is)

max((cell[k], x, y)
    for (y, row) in enumerate(m)
    for (x, cell) in enumerate(row))[1:]

Also, you can assign the result directly to a couple of variables:

(_, x, y) = max((cell[k], x, y)
                for (y, row) in enumerate(m)
                for (x, cell) in enumerate(row))

This is O( n 2 ), btw.

import itertools

indexes = itertools.product( xrange(len(m)), xrange(len(m[0]))
print max(indexes, key = lambda x: m[x[0]][x[1]][k])

or using numpy

import numpy
data = numpy.array(m)
print numpy.argmax(m[:,:,k])

In you are interested in speeding up operations in python, you really need to look at numpy.

Assuming "The Number of Interest" is in a known spot in the list, and there will be a nonzero maximum,

maxCoords = [-1, -1]
maxNumOfInterest = -1
rowIndex = 0
for row in m:
    colIndex = 0
    for entry in row:
        if entry[indexOfNum] > maxNumOfInterest:
            maxNumOfInterest = entry[indexOfNum]
            maxCoords = [rowIndex,colIndex]
        colIndex += 1
    rowIndex += 1

Is a naive method that will be O(n 2 ) on the size of the matrix. Since you have to check every element, this is the fastest solution possible.

@Marcelo's method is more succulent, but perhaps less readable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM