ในบทความนี้ เราจะเรียนรู้เกี่ยวกับวิธีการเริ่มต้นเมทริกซ์โดยใช้รายการสองมิติใน Python 3.x หรือก่อนหน้านั้น
มาดูวิธีที่ใช้งานง่ายในการเริ่มต้นเมทริกซ์ที่มีเฉพาะภาษาไพ ธ อนเท่านั้น ที่นี่เราใช้ประโยชน์จากการทำความเข้าใจรายการ เราเริ่มต้นรายการภายในแล้วขยายไปยังหลายแถวโดยใช้ความเข้าใจรายการ
ตัวอย่าง
# input the number of rows
N = 3
# input the number of columns
M = 3
# initializing the matrix
res = [ [ i*j for i in range(N) ] for j in range(M) ]
# printing the matrix on screen row by row in a single line
print("Inline representation:")
[ [ print(res[i][j] ,end =" ") for i in range(N) ] for j in range(M) ]
print("")
# printing in multiple lines
print("Multiline representation")
for i in range(N):
for j in range(M):
print(res[i][j] ,end =" ")
print("") ผลลัพธ์
Inline representation: 0 0 0 0 1 2 0 2 4 Multiline representation 0 0 0 0 1 2 0 2 4
ทีนี้มาดูวิธีทั่วไปที่สามารถนำไปใช้ในภาษาใดก็ได้ นี่เป็นวิธีมาตรฐานในการสร้างเมทริกซ์หรืออาร์เรย์หลายมิติ
ตัวอย่าง
# input the number of rows
N = 3
# input the number of columns
M = 3
lis=[[0,0,0],[0,0,0],[0,0,0]]
# initializing the matrix
for i in range(N):
for j in range(M):
lis[i][j]=i
# multiline representation
for i in range(N):
for j in range(M):
print(lis[i][j],end=" ")
print("") ผลลัพธ์
0 0 0 0 1 2 0 2 4
บทสรุป
ในบทความนี้ เราได้เรียนรู้วิธีใช้ลอจิกเกตใน Python 3.x ก่อนหน้านี้ นอกจากนี้เรายังได้เรียนรู้เกี่ยวกับเกทสากลสองแห่งเช่นเกท NAND และ NOR