본문 바로가기
  • Hello_
Python/Error

[Python_Error] TypeError: unsupported operand type(s) for -: 'int' and 'list'

by LDwDL 2022. 9. 29.
728x90
반응형

본 포스팅은 업무 중 발생했던 오류들을 예시를 통해 어떻게 해결을 했는지 적을 예정이다.

 

TypeError: unsupported operand type(s) for -: 'int' and 'list'

본 오류는 array 내에 scalar 값이 아닌 list가 들어가서 발생한 오류이다.

 

[예시]

import numpy as np

rand_cube_3D = np.random.randint(0,100,size=[3,3,3])

print(rand_cube_3D)
"""
array([[[87, 58, 63],
        [ 3, 44, 32],
        [81, 11, 80]],

       [[20, 84, 77],
        [56,  8, 32],
        [38, 99, 61]],

       [[71, 83, 58],
        [85, 29, 65],
        [67, 33, 70]]])
"""

 

선언된 3D array를 crop 하기 위해 다음과 같이 중심점과 얼마만큼 crop을 할 건지 margin을 선언해준다. 그 이후 crop을 할 때 오류가 발생했었다.

bbox_center_x = 2
bbox_center_y = 2
bbox_center_z = 2

bbox_margin = [1,0,1]

cropped_cube = rand_cube_3D[bbox_center_x-bbox_margin:bbox_center_x+bbox_margin,
                            bbox_center_y-bbox_margin:bbox_center_y+bbox_margin,
                            bbox_center_z-bbox_margin:bbox_center_z+bbox_margin,]

"""
TypeError                                 Traceback (most recent call last)
----> 1 cropped_cube = rand_cube_3D[bbox_center_x-bbox_margin:bbox_center_x+bbox_margin,
      2                             bbox_center_y-bbox_margin:bbox_center_y+bbox_margin,
      3                             bbox_center_z-bbox_margin:bbox_center_z+bbox_margin,]

TypeError: unsupported operand type(s) for -: 'int' and 'list'
"""

 

[해결]

이는 단순히 rand_cube_3D 내에 index로 int가 입력이 되어야 하는데 bbox_margin이라는 list가 입력이 되었기 때문에 문제가 발생했다. 이는 scalar로 입력을 해주면 쉽게 해결이 된다.

cropped_cube = rand_cube_3D[bbox_center_x-bbox_margin[0]:bbox_center_x+bbox_margin[0],
                            bbox_center_y-bbox_margin[1]:bbox_center_y+bbox_margin[1],
                            bbox_center_z-bbox_margin[2]:bbox_center_z+bbox_margin[2],]
         
print(cropped_cube.shape)
# (2, 0, 2)

 

 

 

728x90
반응형

댓글