[英]Given a 2D list (matrix), how to find the largest element and print its row and column number?
我需要找到 MxN 二维列表中最大元素的行号和列号。 如果不止一个,我想报告行数和列数最小的那个。 如果可能的话,我想在没有 numpy 的情况下进行,因为我仍在尝试通过这些练习来掌握 Python 的窍门。
这是我想做的一个例子:
# 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]]
然后 output 需要是:
[1, 2]
因为前 5是行号和列号最小的最大元素。
我已经找到每行的最大值,但现在我只需要比较每列的值并打印索引。 这是我现在所拥有的:
# 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)
这给了我 output:
4 3
5 2
5 0
我不知道如何继续 go。
当找到更大的数字时,您可以遍历行和列保存索引。
# 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.