เมื่อต้องการลบแถวที่มีตัวเลข ใช้ list comprehension และตัวดำเนินการ 'not' และ 'any'
ตัวอย่าง
สาธิตด้านล่าง:
my_list = [[14, 'Pyt', 'fun'], ['Pyt', 'is', 'best'], [23, 51], ['Pyt', 'fun']]
print("The list is :")
print(my_list)
my_result = [index for index in my_list if not any(isinstance(element, int) for element in index)]
print("The result is :")
print(my_result)
ผลลัพธ์
The list is : [[14, 'Pyt', 'fun'], ['Pyt', 'is', 'best'], [23, 51], ['Pyt', 'fun']] The result is : [['Pyt', 'is', 'best'], ['Pyt', 'fun']]
คำอธิบาย
- กำหนดลิสต์ของลิสต์และแสดงผล
- ใช้ list comprehension วนลูป ตรวจสอบแต่ละ element ว่าเป็น integer ด้วย 'isinstance'
- ถ้าเป็น integer ให้ลบแถวออก
- มิฉะนั้น เก็บไว้ในลิสต์ กำหนดให้ตัวแปร
- แสดงผลลัพธ์บนคอนโซล