티스토리 뷰
Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.
Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.
아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.
How to remove an element from a list by index
인덱스로 리스트에서 아이템 제거하기
문제 내용
How do I remove an element from a list by index?
인덱스 별로 리스트에서 아이템을 제거하려면 어떻게 해야 합니까?
I found list.remove()
, but this slowly scans the list for an item by value.
list.remove()를 찾았지만, 이것은 값 별로 목록을 천천히 스캔한다.
높은 점수를 받은 Solution
Use del
and specify the index of the element you want to delete:
del을 사용하여 삭제할 아이템의 인덱스를 지정합니다.
>>> a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> del a[-1]
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8]
Also supports slices:
슬라이스도 지원합니다.
>>> del a[2:4]
>>> a
[0, 1, 4, 5, 6, 7, 8, 9]
Here is the section from the tutorial.
여기 튜토리얼의 섹션이 있습니다.
가장 최근 달린 Solution
It has already been mentioned how to remove a single element from a list and which advantages the different methods have. Note, however, that removing multiple elements has some potential for errors:
리스트에서 단일 아이템을 제거하는 방법과 다양한 방법이 어떤 이점을 갖는지는 이미 언급되었다. 그러나 여러 아이템을 제거하면 오류가 발생할 수 있습니다.
>>> l = [0,1,2,3,4,5,6,7,8,9]
>>> indices=[3,7]
>>> for i in indices:
... del l[i]
...
>>> l
[0, 1, 2, 4, 5, 6, 7, 9]
Elements 3 and 8 (not 3 and 7) of the original list have been removed (as the list was shortened during the loop), which might not have been the intention. If you want to safely remove multiple indices you should instead delete the elements with highest index first, e.g. like this:
원래 리스트의 아이템 3과 아이템 8(3과 7이 아님)이 제거되었습니다(루프 중에 리스트가 짧아졌기 때문에). 여러 인덱스를 안전하게 제거하려면 다음과 같이 인덱스가 가장 높은 아이템을 먼저 삭제해야 합니다.
>>> l = [0,1,2,3,4,5,6,7,8,9]
>>> indices=[3,7]
>>> for i in sorted(indices, reverse=True):
... del l[i]
...
>>> l
[0, 1, 2, 4, 5, 6, 8, 9]
출처 : https://stackoverflow.com/questions/627435/how-to-remove-an-element-from-a-list-by-index
'개발 > 파이썬' 카테고리의 다른 글
리스트에서 동일 아이템 개수 구하기 (0) | 2022.12.11 |
---|---|
현재 실행 중인 파일의 경로와 이름 가져오기 (0) | 2022.12.10 |
파이썬 딕트에서 'has_key()'와 'in' 중 더 좋은 방법은? (0) | 2022.12.10 |
전체 Pands 시리즈/데이터 프레임 이쁘게 인쇄하기 (0) | 2022.12.10 |
Dictionary 형태의 문자열 표현을 Dictionary로 변환하기 (0) | 2022.12.10 |