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

Python – ลบสมาชิกที่อยู่ในระยะ K จาก N

เมื่อต้องการลบสมาชิกที่อยู่ในระยะ K จากค่า N (คือค่าที่อยู่ระหว่าง N-K ถึง N+K) สามารถใช้ list comprehension พร้อมเงื่อนไขได้

ตัวอย่าง

my_list = [13, 52, 5, 45, 65, 61, 18]
print("The list is :")
print(my_list)
K = 3
print("The value of K is ")
print(K)
N = 5
print("The value of N is ")
print(N)
my_result = [element for element in my_list if element < N - K or element > N + K]
print("The result is:")
print(my_result)

ผลลัพธ์

The list is : [13, 52, 5, 45, 65, 61, 18]
The value of K is 3
The value of N is 5
The result is: [13, 52, 45, 65, 61, 18]

คำอธิบาย

  • กำหนดลิสต์ตัวเลข ค่า K (ระยะ) และ N (จุดศูนย์กลาง)

  • ช่วงที่จะลบ: N-K = 2 ถึง N+K = 8 (คือ 2,3,4,5,6,7,8)

  • ใช้ list comprehension เก็บเฉพาะค่าที่ < 2 หรือ > 8 (อยู่นอกช่วง)

  • ค่า 5 อยู่ในช่วงถูกลบออก แสดงผลลัพธ์ที่เหลือ