เมื่อต้องการดึงแถว (สับลิสต์) ที่สมาชิกทุกตัวเป็นชนิดข้อมูลที่กำหนด (เช่น int) สามารถใช้ list comprehension, isinstance() และ all() ได้
ตัวอย่าง
my_list = [[14, 35, "Will"], [12, 26, 17], ["p", "y", "t"], [29, 40, 21]]
print("The list is :")
print(my_list)
my_data_type = int
my_result = [row for row in my_list if all(isinstance(element, my_data_type) for element in row)]
print("The result is :")
print(my_result)
ผลลัพธ์
The list is : [[14, 35, 'Will'], [12, 26, 17], ['p', 'y', 't'], [29, 40, 21]] The result is : [[12, 26, 17], [29, 40, 21]]
คำอธิบาย
กำหนดเมทริกซ์ข้อมูลผสมและชนิดข้อมูลที่ต้องการ (my_data_type = int)
ใช้ list comprehension กรองแถวที่
all(isinstance(element, my_data_type) for element in row)ตรวจสอบว่าสมาชิกทุกตัวในแถวเป็น int หรือไม่
แสดงผลลัพธ์เฉพาะแถวที่เป็น int ทั้งหมด