简体   繁体   中英

how to find minimum score of a 2d array?

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?

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]]

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM