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

Python – หาองค์ประกอบที่อยู่ติดกัน (Adjacent Elements) ในลิสต์


เมื่อต้องการแสดงองค์ประกอบที่อยู่ติดกันในลิสต์ ใช้เมธอดที่ใช้ enumerate และการวนลูปง่ายเพื่อหาผลลัพธ์

ตัวอย่าง

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

def find_adjacent_elements(my_list): 
    my_result = [] 
    for index, ele in enumerate(my_list): 
        if index == 0: 
            my_result.append((None, my_list[index + 1])) 
        elif index == len(my_list) - 1: 
            my_result.append((my_list[index - 1], None)) 
        else: 
            my_result.append((my_list[index - 1], my_list[index + 1])) 
    return my_result 
my_list = [13, 37, 58, 12, 41, 25, 48, 19, 23] 
print("The list is:") 
print(my_list) 
print("The result is :") 
print(find_adjacent_elements(my_list))

ผลลัพธ์

The list is: [13, 37, 58, 12, 41, 25, 48, 19, 23] 
The result is : [(None, 37), (13, 58), (37, 12), (58, 41), (12, 25), (41, 48), (25, 19), (48, 23), (19, None)]

คำอธิบาย

  • กำหนดเมธอด 'find_adjacent_elements' รับลิสต์ พารามิเตอร์ enumerate ลิสต์
  • สร้างลิสต์ว่าง
  • วนลูปด้วย 'enumerate' ตาม index คืนค่าตัวก่อนและตัวหลัง
  • ถ้า index 0 ให้คืน (None, ตัวถัดไป)
  • ถ้า index สุดท้าย ให้คืน (ตัวก่อน, None)
  • อื่นๆ คืน (ตัวก่อน, ตัวถัดไป)
  • นอกเมธอด กำหนดลิสต์แสดงผล เรียกเมธอด แสดงผลลัพธ์