728x90
반응형
본 포스팅은 업무 중 발생했던 오류들을 예시를 통해 어떻게 해결을 했는지 적을 예정이다.
TypeError: slice indices must be integers or None or have
an __index__ method
해당 오류는 list를 슬라이싱 할 때 int의 조합이 아니라 실수의 조합으로 입력이 되면 발생하는 오류이다. 필자는 //을 사용하여 입력을 정수로 만들고 슬라이싱을 진행하고자 했으나 float로 출력이 되어서 발생했던 오류이다.
[예시]
import numpy as np
rand = [77, 84, 39, 42, 64]
print(rand)
# [77, 84, 39, 42, 64]
ori_idx = np.array([3.,9.])
half_idx = ori_idx // 2
print(half_idx)
# array([1., 4.]) # type : float
rand[half_idx[0]:half_idx[1]]
"""
TypeError Traceback (most recent call last)
----> 1 rand[half_idx[0]:half_idx[1]]
TypeError: slice indices must be integers or None or have an __index__ method
"""
[해결]
해결 방법은 slicing에 사용되어지는 변수를 모두 정수로 변환하면 해결된다.
half_idx_int = np.array(half_idx).astype(np.uint8)
print(half_idx_int)
# array([1, 4], dtype=uint8)
rand[half_idx_int[0]:half_idx_int[1]]
# [84, 39, 42]
728x90
반응형
댓글