การลบองค์ประกอบเดียวออกจากไพ ธ อนนั้นตรงไปตรงมาโดยใช้ดัชนีขององค์ประกอบและฟังก์ชันเดล แต่อาจมีบางกรณีที่เราต้องลบองค์ประกอบสำหรับกลุ่มดัชนี บทความนี้สำรวจวิธีการลบเฉพาะองค์ประกอบที่อยู่ในรายการซึ่งระบุไว้ในรายการดัชนี
การใช้ sort and del
ในแนวทางนี้ เราสร้างรายการที่มีค่าดัชนีที่ต้องลบออก เราจัดเรียงและย้อนกลับเพื่อรักษาลำดับดั้งเดิมขององค์ประกอบของรายการ สุดท้ายเราใช้ฟังก์ชัน del กับรายการที่กำหนดเดิมสำหรับจุดดัชนีเฉพาะเหล่านั้น
ตัวอย่าง
Alist = [11,6, 8, 3, 2]
# The indices list
idx_list = [1, 3, 0]
# printing the original list
print("Given list is : ", Alist)
# printing the indices list
print("The indices list is : ", idx_list)
# Use del and sorted()
for i in sorted(idx_list, reverse=True):
del Alist[i]
# Print result
print("List after deleted elements : " ,Alist) ผลลัพธ์
การเรียกใช้โค้ดข้างต้นทำให้เราได้ผลลัพธ์ดังต่อไปนี้ -
Given list is : [11, 6, 8, 3, 2] The indices list is : [1, 3, 0] List after deleted elements : [8, 2]
idx_list หลังจากเรียงลำดับและย้อนกลับจะกลายเป็น [0,1,3] ดังนั้นเฉพาะองค์ประกอบจากตำแหน่งเหล่านี้เท่านั้นที่จะถูกลบ
ใช้ enumerate และไม่อยู่ใน
เรายังเข้าถึงโปรแกรมข้างต้นได้โดยใช้ enumerate และ a not in clause ใน a for loop ผลลัพธ์ก็เหมือนกับด้านบน
ตัวอย่าง
Alist = [11,6, 8, 3, 2]
# The indices list
idx_list = [1, 3, 0]
# printing the original list
print("Given list is : ", Alist)
# printing the indices list
print("The indices list is : ", idx_list)
# Use slicing and not in
Alist[:] = [ j for i, j in enumerate(Alist)
if i not in idx_list ]
# Print result
print("List after deleted elements : " ,Alist) ผลลัพธ์
การเรียกใช้โค้ดข้างต้นทำให้เราได้ผลลัพธ์ดังต่อไปนี้ -
Given list is : [11, 6, 8, 3, 2] The indices list is : [1, 3, 0] List after deleted elements : [8, 2]