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

ดึงคอลัมน์ที่ N ของ Matrix ใน Python


ตรวจสอบว่ามีค่าเฉพาะอยู่ในคอลัมน์ที่ N ของ Matrix หรือไม่ ใช้ any() กับ Generator Expression

ตัวอย่างโค้ด

matrix = [[34, 67, 89], [16, 27, 86], [48, 30, 0]]
print("Matrix:", matrix)

N = 1  # 0-based index (คอลัมน์ที่ 2)
target = 30
print("Column index:", N)
print("Target value:", target)

exists = any(row[N] == target for row in matrix)
print(f"Exists in column {N}?:", exists)

ผลลัพธ์

Matrix: [[34, 67, 89], [16, 27, 86], [48, 30, 0]]
Column index: 1
Target value: 30
Exists in column 1?: True

คำอธิบาย

  • Matrix เป็นลิสต์ของลิสต์ (rows)

  • row[N] เข้าถึงคอลัมน์ N ของแต่ละ row

  • any(...) คืน True ถ้ามีอย่างน้อย 1 ตรง

  • Short-circuit: หยุดทันทีที่เจอ True

  • ได้ row[2][1] = 30 ตรง target → True