Bài toán: Tiêu đề nói dictionary nhưng code demo với list. Tìm giá trị lớn thứ 2.
Cách 1: Dùng sorted() và chỉ mục âm
example_dict = {"tutor": 3, "tutorials": 15, "point": 9, "tutorialspoint": 19}
print(list(sorted(example_dict.values()))[-2])
15
Cách 2: Dùng sort() trên list
list1 = [11, 22, 1, 2, 5, 67, 21, 32]
list1.sort()
print("Second largest element in the list is:", list1[-2])
Second largest element in the list is: 32
Cách 3: Brute-force không dùng hàm tích hợp
list1 = [11, 22, 1, 2, 5, 67, 21, 32]
max_ = max(list1[0], list1[1])
secondmax = min(list1[0], list1[1])
for i in range(2, len(list1)):
if list1[i] > max_:
secondmax = max_
max_ = list1[i]
else:
if list1[i] > secondmax:
secondmax = list1[i]
print("Second highest number is the list is:", str(secondmax))
Second highest number is the list is: 32
Kết luận
Đã xem 3 cách tìm giá trị lớn thứ 2 (trên list). Lưu ý tiêu đề đề cập dictionary nhưng code dùng list.