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

หาความต่างของคอลัมน์ที่ N ติดกันใน Tuple List ด้วย Python

เมื่อต้องการหาความต่างของคอลัมน์ที่ N (Nth column) ระหว่าง tuple ติดกันใน list of tuples สามารถวนลูปคำนวณความต่างสัมบูรณ์ (absolute difference)

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

my_list = [(67, 89, 32), (11, 23, 44), (65, 75, 88)]
print("The list is:")
print(my_list)
print("The value of k has been initialized")
K = 1
my_result = []
for idx in range(0, len(my_list) - 1):
    my_result.append(abs(my_list[idx][K] - my_list[idx + 1][K]))
print("The resultant list of tuple is:")
print(my_result)

ผลลัพธ์

The list is: [(67, 89, 32), (11, 23, 44), (65, 75, 88)]
The value of k has been initialized
The resultant list of tuple is: [66, 52]

คำอธิบาย

  • กำหนด list of tuples และค่า K (index ของคอลัมน์ เริ่มจาก 0)

  • K = 1 หมายถึงคอลัมน์ที่ 2 (ค่า 89, 23, 75)

  • วนลูป idx จาก 0 ถึง len-2 (คู่ tuple ติดกัน)

  • คำนวณ abs(my_list[idx][K] - my_list[idx+1][K]) และ append เข้า my_result

  • ผลลัพธ์: |89-23| = 66, |23-75| = 52

วิธีเขียนสั้นกว่าด้วย list comprehension:

my_result = [abs(my_list[i][K] - my_list[i+1][K]) for i in range(len(my_list)-1)]

การประยุกต์: เทคนิคนี้ใช้ได้กับ time series data, คำนวณอัตราการเปลี่ยนแปลง, หรือ feature engineering