Open kim-irubi opened 2 years ago
n = len(result)
for i in range(n):
if result.count(result_list[i]) > 1:
result.remove(result[i])
n -= 1
위 코드에서 n을 1 줄이면 반복문의 i도 같이 줄어든 n까지 반복한다고 생각하신 것 같습니다. 하지만, 실제 코드를 테스트해보시면 n의 값은 1이 줄어들지만 반복문을 도는 i 에는 영향을 주지 않음을 확인하실 수 있습니다. 따라서 리스트의 갯수는 줄어드는데 i는 처음 할당받은 n-1 까지 받으려하니 out of range가 뜨는 것입니다.
아래 코드처럼 i와 n을 print 하면서 확인해보시면 도움이 되실 것 같네요 !
a = ["a", "b", "a"]
n = len(a)
for i in range(n):
print(i)
if a.count(a[i]) > 1:
a.remove(a[i])
n -= 1
print(n)
이해했습니다 감사합니다!!!
if result.count(result_list[i]) > 1 에서 list index out of range 오류가 뜨는데 왜 뜨는지 이해가 되질 않습니다.