I want to ask how to find max and min score in Multi-dimensional array in Python
arraylist = [[10, 9, 5], [10, 6, 10], [10, 10, 10], [10, 10, 9]]
s = 0
for r in arraylist:
s = s len(r)-2
avg = sum(r)/len(r)
print("Avg score Student", s, "=", avg)
indexmax = arraylist.index(max(avg))
print("find max score", indexmax 1, "with score", max(avg))
CodePudding user response:
You can use the max()
function with the key
argument to find the row with the maximum average.
maxrow = max(arraylist, key=lambda row:sum(row)/len(row))
indexmax = arraylist.index(maxrow)
CodePudding user response:
Why are you relying on this logic:
s=s len(r)-2
to enumerate the students? Shouldn't you simply use a s = 1
?
Anyway, I would do as follows:
avgs = [sum(x) / len(x) for x in arraylist]
for n_student, score in enumerate(avgs):
print(f'"Average score student{n_student 1} = {score}')
print(f'Best is student{avgs.index(max(avgs)) 1} with score {max(avgs)}')
You'll need to manage situations when you have more than one best student, but this is a concise starting point.
CodePudding user response:
Using numpy can help a lot here. It is much easier and efficient in comparison to simple list in python.
import numpy as np
arraylist = [[10, 9, 5], [10, 6,10], [10, 10, 10], [10,10,9]]
arraylist = np.array(arraylist)
# or we can keep the main list in list format and set the np array to another variable in order to prevent re-converting to a list (if needed)
print(np.min(arraylist))
print(np.max(arraylist))
print(arraylist)
# you can re-convert it to a list by the below method:
arraylist = arraylist.tolist()
print(arraylist)