I need to find the row and column number for the largest element of an MxN 2D list. 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.
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:
[1, 2]
As the first 5 is the largest element with the smallest row and column number.
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:
4 3
5 2
5 0
I have no idea how to go on further.
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)
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.