Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

หาทัพเพิลที่ใกล้เคียง K-th index มากที่สุดใน Python


เมื่อต้องการหาทัพเพิลในลิสต์ที่มีค่าใน index K ใกล้เคียงกับค่าใน index K ของทัพเพิลอ้างอิงมากที่สุด ใช้ enumerate และ abs()

ตัวอย่างโค้ด

my_list = [(5, 6), (66, 76), (21, 35), (90, 8), (9, 0)]
print("The list is:")
print(my_list)

target = (17, 23)
print("The target tuple is:")
print(target)

K = 2
print("The value of K is:", K)

min_diff = float('inf')
closest_idx = None

for idx, val in enumerate(my_list):
    diff = abs(target[K - 1] - val[K - 1])
    if diff < min_diff:
        min_diff = diff
        closest_idx = idx

print("The tuple nearest to Kth index element is:")
print(my_list[closest_idx])

ผลลัพธ์

The list is: [(5, 6), (66, 76), (21, 35), (90, 8), (9, 0)]
The target tuple is: (17, 23)
The value of K is: 2
The tuple nearest to Kth index element is: (21, 35)

คำอธิบาย

  • K = 2 หมายถึงดู index 1 (0-based) คือองค์ประกอบที่ 2

  • target[1] = 23 เปรียบเทียบกับ val[1] ของแต่ละทัพเพิล

  • ใช้ abs() หาความต่างสัมบูรณ์

  • เก็บ index ที่มีความต่างน้อยที่สุด

  • (21, 35) มีค่า index 1 = 35 ใกล้ 23 มากที่สุด (diff = 12)