DPlagueis
DPlagueis

Reputation: 67

Finding the index of the maximum value of nested lists Python 3.x

I am trying to find the index of the maximum value of nested lists.

I have three lists [[1,2,3,4], [5,6,7,8], [9,10,11,12]]

and I would like my output to give me the index of the value 12

the out put would read:

The location of the largest element is at (2,3).

Thanks!

Upvotes: 1

Views: 2099

Answers (5)

Steven Summers
Steven Summers

Reputation: 5384

If you want a solution that will work for any depth of nested lists, then you can try this.

def find_index_of_max(nested_lst):
    _max, idx_path, cpath = None, None, []

    def find_max(lst, depth = 0):
        nonlocal idx_path, _max
        if len(cpath) - 1 < depth:
            cpath.append(0)

        for i, val in enumerate(lst):
            cpath[depth] = i
            if _max is None or val > _max:
                idx_path = tuple(cpath)
                _max = val
            elif isinstance(val, list):
                find_max(val, depth + 1)

    find_max(nested_lst)
    return idx_path

#Output
>>> find_index_of_max([[1,2,3,4], [5,6,7,8], [9,10,11,12]])
(2, 3)
>>> find_index_of_max([[1,2,[16, [17, 18], 3], 3,4], [5,6,7,8], [9,10,11,12]])
(0, 2, 1, 1)

Upvotes: 0

plasmon360
plasmon360

Reputation: 4199

mylist1 = [[1,2,3,4], [5,6,7,8], [9,10,11,12]]
mylist2 = [[1,1,1,1,9], [5,5,5,5,5]] 

def myfunc(mylist):
    xx =  mylist.index(max(mylist, key = lambda x:max(x)))
    yy =  mylist[xx].index(max(mylist[xx]))
    print(xx,yy)

myfunc(mylist1)
myfunc(mylist2)

returns

(2, 3)
(0, 4)

Upvotes: 0

Steve Mayne
Steve Mayne

Reputation: 22818

If you don't want to use numpy, you can do the search manually like this:

a = [[1,2,3,4], [5,6,7,8], [9,10,11,12]]

maxEntry = None
coords = (None, None)
for x, sublist in enumerate(a):
    for y, entry in enumerate(sublist):
        if maxEntry == None or entry > maxEntry:
            maxEntry = entry
            coords = (x,y)

print(coords)

Upvotes: 0

Hans
Hans

Reputation: 2492

a solution without numpy would be (assuming the list and its first element are never empty):

def maxIndex(nestedList):
    m = (0,0)
    for i in range(len(nestedList)):
        for j in range(len(nestedList[i])):
            if nestedList[i][j] > nestedList[m[0]][m[1]]:
                m = (i,j)
    return m

Upvotes: 0

wim
wim

Reputation: 362557

Using numpy's argmax and then unravel the index:

>>> L = [[1,2,3,4], [5,6,7,8], [9,10,11,12]]
>>> a = np.array(L)
>>> np.unravel_index(np.argmax(a), a.shape)
(2, 3)

Upvotes: 3

Related Questions