简体   繁体   English

给定一个二维列表(矩阵),如何找到最大的元素并打印它的行号和列号?

[英]Given a 2D list (matrix), how to find the largest element and print its row and column number?

I need to find the row and column number for the largest element of an MxN 2D list.我需要找到 MxN 二维列表中最大元素的行号和列号。 If there is more than on, I want to report the one with the smallest row and column number.如果不止一个,我想报告行数和列数最小的那个。 If possible, I want to do it without numpy as I am still trying to get the hang of Python by doing these exercises.如果可能的话,我想在没有 numpy 的情况下进行,因为我仍在尝试通过这些练习来掌握 Python 的窍门。

Here is an example of what I would like to do:这是我想做的一个例子:

# m rows and n integers (columns)
m = 3
n = 4
# The 2D-list
arr = [[0, 3, 2, 4],
       [2, 3, 5, 5],
       [5, 1, 2, 3]]

And the output would then need to be:然后 output 需要是:

[1, 2]

As the first 5 is the largest element with the smallest row and column number.因为前 5是行号和列号最小的最大元素。

I have gotten as far as finding the largest value per row, but now I just need to compare this per column and the print the indices.我已经找到每行的最大值,但现在我只需要比较每列的值并打印索引。 This is what I have up to now:这是我现在所拥有的:

# m rows and n integers (columns)
m = 3
n = 4
MxN = [m, n]
# The 2D-list
arr = [[0, 3, 2, 4],
       [2, 3, 5, 5],
       [5, 1, 2, 3]]

for i in range(MxN[0]):
    row = arr[i]
    maxValue = max(row)
    index = row.index(maxValue)
    print(maxValue, index)

Which gives me the output:这给了我 output:

4 3
5 2
5 0

I have no idea how to go on further.我不知道如何继续 go。

You can just iterate over rows and columns save the index when find a larger number.当找到更大的数字时,您可以遍历行和列保存索引。

# m rows and n integers (columns)
m = 3
n = 4
MxN = [m, n]
# The 2D-list
arr = [[0, 3, 2, 4],
       [2, 3, 5, 5],
       [5, 1, 2, 3]]

max_num = float("-inf")
index = [-1, -1]

for i in range(MxN[0]):
    for j in range(MxN[1]):
        if arr[i][j] > max_num:
            max_num = arr[i][j]
            index = [i, j]

print(index)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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