2차원 리스트/튜플
2차원 리스트/튜플은 여러 개의 리스트/튜플을 포함하는 자료구조로, 행과 열로 이루어진 표 형태의 데이터를 표현할 때 자주 사용됩니다.
다양한 상황에서 2차원 리스트/튜플을 활용하여 데이터를 효과적으로 다룰 수 있습니다.
1. 2차원 리스트/튜플의 생성
2차원 리스트/튜플을 생성하는 방법에는 여러 가지가 있습니다.
가장 간단한 방법은 대괄호([])를 사용하여 리스트 안에 리스트를 넣는 것입니다.
예를 들어, 다음과 같이 2차원 리스트를 생성할 수 있습니다.
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
matrix
# [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
2차원 튜플을 생성할 때는 소괄호(())를 사용하여 튜플 안에 튜플을 넣습니다.
예를 들어, 다음과 같이 2차원 튜플을 생성할 수 있습니다.
matrix = (
(1, 2, 3),
(4, 5, 6),
(7, 8, 9)
)
matrix
# ((1, 2, 3), (4, 5, 6), (7, 8, 9))
2. 2차원 리스트/튜플의 접근
2차원 리스트/튜플의 원소에 접근하기 위해서는 인덱스를 사용합니다.
첫 번째 인덱스는 행을, 두 번째 인덱스는 열을 나타냅니다.
예를 들어, 위에서 생성한 2차원 리스트의 첫 번째 행의 첫 번째 열에 접근하려면 다음과 같이 인덱스를 사용합니다.
value = matrix[0][0]
# 1
3. 2차원 리스트/튜플의 순회
2차원 리스트/튜플의 모든 원소에 접근하기 위해서는 반복문을 사용합니다.
중첩된 반복문을 사용하여 행과 열을 순회할 수 있습니다.
예를 들어, 2차원 리스트의 모든 원소를 출력하는 코드는 다음과 같습니다.
for row in matrix:
for element in row:
print(element)
# 1
# 2
# 3
# 4
# 5
# 6
# 7
# 8
# 9
4. 2차원 리스트/튜플의 크기 확인
2차원 리스트/튜플의 행과 열의 개수를 확인하기 위해서는 내장 함수인 `len()`을 사용합니다.
예를 들어, 2차원 리스트의 행의 개수를 구하는 코드는 다음과 같습니다.
num_rows = len(matrix)
# 3
5. 2차원 리스트/튜플의 수정
2차원 리스트/튜플의 특정 위치에 있는 원소를 수정하기 위해서는 인덱스를 사용합니다. 예를 들어, 위에서 생성한 2차원 리스트의 두 번째 행의 세 번째 열의 값을 수정하려면 다음과 같이 할 수 있습니다.
matrix[1][2] = 10
이렇게 2차원 리스트/튜플을 수정하면 해당 위치의 원소가 변경됩니다.
잘못된 정보는 댓글로 알려주시면 감사하겠습니다.
'Python' 카테고리의 다른 글
Python - 12. 파이썬의 딕셔너리 (Dictionary) (0) | 2023.07.14 |
---|---|
Python - 11. 파이썬의 집합(Set) (0) | 2023.07.13 |
Python - 9. 파이썬 튜플(tuple), 불변한(Immutable)한 자료구조. (0) | 2023.07.11 |
Python - 8. 리스트 내포(List Comprehension) (0) | 2023.07.10 |
Python - 7. 파이썬의 List (0) | 2023.07.09 |