본문 바로가기
Python and Django

Python 이차원배열 생성 방법

by leo21c 2012. 10. 18.
SMALL

가로, 세로 크기 만큼의 2차원 배열을 만들 경우 아래와 같이 테스트를 할 수 있다.

 #create width x height matrix
matrix = [[0 for col in range(width)] for row in range(height)]

for row in range(height):
  for col in range(width):
    matrix[row][col] = 0
    if col == 0 and row == 0: matrix[row][col] = 1
    if col == width-1 and row == height-1: matrix[row][col] = 20

for row in matrix:
  print row


만약 가로 크기 3, 세로 5의 크기를 가지고 있을 경우 아래와 같은 결과가 출력된다.

width =3, height = 5

 [1, 0, 0]
 [0, 0, 0]
 [0, 0, 0]
 [0, 0, 0]
 [0, 0, 1]


LIST