Reputation: 5
How to find minimum score of a 2d array
.
My array is like :
[['john', 20], ['jack', 10], ['tom', 15]]
I want find the minimum score of student and print
his name.
tell me how to write that?
Upvotes: 0
Views: 135
Reputation: 4630
If you want to get only one student:
student_details = [['john', 20], ['jack', 10], ['tom', 15]]
student_detail_with_min_score = min(student_details, key=lambda detail: detail[1])
print(student_detail_with_min_score)
print(student_detail_with_min_score[0])
print(student_detail_with_min_score[1])
Output:
['jack', 10]
jack
10
min
function finds the minimum of student_details
, but it will use student_details[i][1]
as the key while comparing.
Read the official documentation to understand how the min
function works with the key
argument.
If you want to get all the students with the minimum score:
student_details = [['rock', 10], ['john', 20], ['jack', 10], ['tom', 15]]
min_score = min(student_details, key=lambda detail: detail[1])[1]
student_details_with_min_score = [
student_detail for student_detail in student_details if student_detail[1] == min_score
]
print(student_details_with_min_score)
Output:
[['rock', 10], ['jack', 10]]
Upvotes: 1