Prepare > Python > Numpy > Shape and Reshape
2023. 8. 27. 20:32ㆍHackerRank-Python
Shape and Reshape | HackerRank
Using the shape and reshape tools available in the NumPy module, configure a list according to the guidelines.
www.hackerrank.com
문제
Task
You are given a space separated list of nine integers. Your task is to convert this list into a 3X3 NumPy array.
Input Format
A single line of input containing 9 space separated integers.
Output Format
Print the 3X3 NumPy array.
=> 숫자 9개 줄테니까 2차원 3x3배열 numpy array로 출력해라.
코드
import numpy as np
N = list(map(int, input().split()))
my_arr = np.array(N)
print(np.reshape(my_arr, (3,3)))
노트
shape
import numpy
my__1D_array = numpy.array([1, 2, 3, 4, 5])
print(my_1D_array.shape) #(5,) -> 1 row and 5 columns
my__2D_array = numpy.array([[1, 2],[3, 4],[6,5]])
print(my_2D_array.shape) #(3, 2) -> 3 rows and 2 columns
- array의 차원을 알려줌
shape = ( )
import numpy
change_array = numpy.array([1,2,3,4,5,6])
change_array.shape = (3, 2)
print(change_array)
#Output
[[1 2]
[3 4]
[5 6]]
- array를 입력한 차원으로 재배열 함
- 기존 array가 변하는 것
reshape(array, ( ))
import numpy
my_array = numpy.array([1,2,3,4,5,6])
print(numpy.reshape(my_array,(3,2)))
#Output
[[1 2]
[3 4]
[5 6]]
- 입력한 차원으로 배열해 새로운 array생성
- 기존 array는 변함 없음
더보기
import numpy as np
N = list(map(int, input().split()))
my_arr = np.array(N)
print(N) # [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(my_arr) # [1 2 3 4 5 6 7 8 9]
print(my_arr.shape) # (9,)
print(np.reshape(my_arr, (3,3)))
print(my_arr) # 기존 array는 그대로 보존
"""
[[1 2 3]
[4 5 6]
[7 8 9]]
"""
# [1 2 3 4 5 6 7 8 9]
my_arr.shape = (3,3)
print(my_arr) # 기존 array 변형
"""
[[1 2 3]
[4 5 6]
[7 8 9]]
"""
두 번째 시도
import numpy
my_arr = numpy.array(list(map(int, input().split())))
new_arr = numpy.reshape(my_arr, (3,3))
print(new_arr)
'HackerRank-Python' 카테고리의 다른 글
Prepare > Python > Numpy > Concatenate (0) | 2023.08.29 |
---|---|
Prepare > Python > Numpy > Transpose and Flatten (0) | 2023.08.28 |
Prepare > Python > Numpy > Arrays (0) | 2023.08.26 |
Prepare > Python > Python Functionals > Map and Lambda Function (0) | 2023.08.25 |
Prepare > Python > Errors and Exceptions > Incorrect Regex (0) | 2023.08.24 |