โปรแกรมนี้ตรวจสอบแต่ละแถวในลิสต์ซ้อน (matrix) ว่ามีชนิดข้อมูล (data type) ต่างกันทุกคอลัมน์หรือไม่ โดยใช้ set() เก็บ type ที่ไม่ซ้ำกัน แล้วเปรียบเทียบจำนวน type กับจำนวนคอลัมน์
ตัวอย่างโค้ด
matrix = [
[4, 2, 6], # ทั้งหมด int -> ไม่ผ่าน
["python", 2, {6: 2}], # str, int, dict -> ผ่าน (3 types)
[3, 1, "fun"], # int, int, str -> ไม่ผ่าน (2 types)
[9, (4, 3)] # int, tuple -> ผ่าน (2 types)
]
print("Matrix ต้นฉบับ:")
for row in matrix:
print(row)
result = []
for row in matrix:
types = set(type(x) for x in row)
if len(types) == len(row):
result.append(row)
print("\nแถวที่มีชนิดข้อมูลต่างกันทุกคอลัมน์:")
for row in result:
print(row)
ผลลัพธ์
Matrix ต้นฉบับ:
[4, 2, 6]
['python', 2, {6: 2}]
[3, 1, 'fun']
[9, (4, 3)]
แถวที่มีชนิดข้อมูลต่างกันทุกคอลัมน์:
['python', 2, {6: 2}]
[9, (4, 3)]
แถวที่ 2 และ 4 ผ่านเกณฑ์ เพราะแต่ละคอลัมน์มี type ต่างกันครบ