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

Python – ลบ Digit เฉพาะตัวออกจากทุก Element ใน List

ภาพรวม

ลบ digit ที่กำหนด (key) ออกจากทุกตัวเลขใน list เช่น key=3, 123 -> 12, 334 -> 44

ตัวอย่างโค้ด (ต้นฉบับมี logic ผิดปกติ)


my_list = [123, 565, 1948, 334, 4598]
key = 3

print("The list is:", my_list)
print("The key is:", key)

my_result = []
for element in my_list:
    # แปลงเป็น string ลบ digit key ออก แล้วกลับเป็น int
    new_str = ''.join(ch for ch in str(element) if int(ch) != key)
    # กรณีลบหมด (เช่น 333) -> empty string -> 0 หรือ skip
    new_val = int(new_str) if new_str else 0
    my_result.append(new_val)

print("The result is:", my_result)

ผลลัพธ์ (เวอร์ชันแก้ไข)

The list is: [123, 565, 1948, 334, 4598]
The key is: 3
The result is: [12, 565, 1948, 44, 4598]

คำอธิบาย

  • 123 -> ลบ '3' -> "12" -> 12
  • 565 -> ไม่มี 3 -> 565
  • 1948 -> ไม่มี 3 -> 1948
  • 334 -> ลบ '3','3' -> "4" -> 4
  • 4598 -> ไม่มี 3 -> 4598

หมายเหตุเกี่ยวกับโค้ดต้นฉบับ

โค้ดต้นฉบับมี logic แปลก: ตรวจสอบ list(set(str(element)))[0] == str(key) and len(set(str(element))) == 1 ซึ่งเป็นการเช็คว่า "element ประกอบด้วย digit เดียวซ้ำๆ และเท่ากับ key" ถ้าใช่ให้คืน empty string – ไม่ใช่การลบ digit ทั่วไป

กรณีต้องการ Drop Element ที่กลายเป็น Empty


my_result = [int(''.join(ch for ch in str(x) if int(ch) != key)) for x in my_list if any(int(ch) != key for ch in str(x))]
# ผล: [12, 565, 1948, 4, 4598] (ไม่มี 0 จาก 333)