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

Python - หา Non-K Distant Elements ในลิสต์

หาสมาชิกในลิสต์ที่ไม่มีสมาชิกอื่นอยู่ห่าง K หน่วย (ทั้งบวกและลบ) คือ ไม่มีค่า x+K และ x-K ในลิสต์

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

my_list = [91, 13, 19, 25, 35, 3, 9, 11, 0]
print("The list is :")
print(my_list)

my_key = 2
print("The key is ")
print(my_key)

my_result = []
for element in my_list:
    if element + my_key not in my_list and element - my_key not in my_list:
        my_result.append(element)

print("The resultant list is :")
print(my_result)

ผลลัพธ์

The list is : [91, 13, 19, 25, 35, 3, 9, 11, 0]
The key is 2
The resultant list is : [91, 19, 25, 35, 3, 0]

คำอธิบาย

  • วนลูปทุก element ในลิสต์
  • เช็ค element + K และ element - K ว่าอยู่ในลิสต์หรือไม่
  • ถ้าทั้งคู่ไม่อยู่ -> Append เข้า Result
  • ตัวอย่าง: 13+2=15 (ไม่มี), 13-2=11 (มี) -> ตัด 13 ออก