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

Python – กรองแถวที่เป็น Immutable เพื่อเป็น Dictionary Keys จากเมทริกซ์

เมื่อต้องการกรองแถวในเมทริกซ์ที่สมาชิกทุกตัวเป็น immutable type (เหมาะเป็น dictionary keys) สามารถใช้ list comprehension และ isinstance() ได้

ตัวอย่าง

my_list = [[24, 15, [32, 33, 12]], ["pyt", 8, (14, 54)], [{15: 24}, 13, "fun"], [True, "cool"]]
print("The list is :")
print(my_list)
my_result = [row for row in my_list if all(isinstance(element, (int, bool, float, tuple, str)) for element in row)]
print("The result is :")
print(my_result)

ผลลัพธ์

The list is : [[24, 15, [32, 33, 12]], ['pyt', 8, (14, 54)], [{15: 24}, 13, 'fun'], [True, 'cool']]
The result is : [['pyt', 8, (14, 54)], [True, 'cool']]

คำอธิบาย

  • กำหนดเมทริกซ์ที่มีข้อมูลหลายประเภท (ลิสต์, tuple, dict, bool, str, int) แสดงผล

  • ใช้ list comprehension กรองแถวที่ all(isinstance(element, (int, bool, float, tuple, str)) ...)

  • ตรวจสอบว่าสมาชิกทุกตัวเป็น immutable type (int, bool, float, tuple, str) ไม่รวม list, dict

  • แถวที่ 2 และ 4 ผ่านเงื่อนไข แถวที่ 1 มี list, แถวที่ 3 มี dict

  • แสดงผลลัพธ์แถวที่ผ่าน