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

Python – หาตำแหน่งที่ใกล้ที่สุดระหว่างสององค์ประกอบในลิสต์


เมื่อต้องการหาตำแหน่งที่ใกล้ที่สุดระหว่างสององค์ประกอบในลิสต์ ใช้เมธอดที่รับสามพารามิเตอร์ ใช้ 'not in' และ list comprehension เพื่อหาผลลัพธ์

สาธิตด้านล่าง:

ตัวอย่าง

def nearest_occurence_list(my_list, x, y): 
    if x not in my_list or y not in my_list: 
        return -1 
    x_index = [index for index in range(len(my_list)) if my_list[index] == x] 
    y_index = my_list.index(y) 
    min_dist = 1000000 
    result = None 
    for element in x_index: 
        if abs(element - y_index) < min_dist: 
            result = element 
            min_dist = abs(element - y_index) 
    return result 
my_list = [12, 24, 15, 17, 28, 26, 13, 28, 14, 12, 20, 19, 24, 29, 14] 
print("The list is :") 
print(my_list) 
x = 14 
print("The value of x is ") 
print(x) 
y = 26 
print("The value of y is ") 
print(y) 
print("The result is :") 
print(nearest_occurence_list(my_list, x, y))

ผลลัพธ์

The list is : [12, 24, 15, 17, 28, 26, 13, 28, 14, 12, 20, 19, 24, 29, 14] 
The value of x is 14 
The value of y is 26 
The result is : 8

คำอธิบาย

  • กำหนดเมธอด 'nearest_occurence_list' รับสามพารามิเตอร์
  • ถ้าพารามิเตอร์ที่ 2 หรือ 3 ไม่อยู่ในพารามิเตอร์แรก คืนค่า -1
  • ใช้ list comprehension หา index ทั้งหมดของ x
  • หา index ของ y (ครั้งแรก)
  • วนลูป index ของ x หาระยะห่างน้อยที่สุดกับ y_index
  • คืนค่า index ของ x ที่ใกล้ที่สุด
  • นอกเมธอด กำหนดลิสต์ x y เรียกเมธอด แสดงผล