[英]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.