개발/파이썬

값에 따라 리스트 아이템을 삭제하는 쉬운 방법

맨날치킨 2022. 12. 14. 19:05
반응형

Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.

Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.

 

아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.

Is there a simple way to delete a list element by value?

값에 따라 리스트 아이템을 삭제하는 간단한 방법이 있나요?

 문제 내용 

I want to remove a value from a list if it exists in the list (which it may not).

목록에 값이 있는 경우 리스트에서 값을 제거합니다.(그렇지 않을 수도 있음).
a = [1, 2, 3, 4]
b = a.index(6)

del a[b]
print(a)

 

The above gives the error:

위의 오류는 다음과 같습니다.
ValueError: list.index(x): x not in list

 

So I have to do this:

그래서 저는 이것을 해야 합니다:
a = [1, 2, 3, 4]

try:
    b = a.index(6)
    del a[b]
except:
    pass

print(a)

 

But is there not a simpler way to do this?

하지만 이것을 하는 더 간단한 방법은 없을까요?

 

 

 

 높은 점수를 받은 Solution 

To remove the first occurrence of an element, use list.remove:

일치하는 첫번 째 아이템을 제거하려면 list.remove를 사용하세요.
>>> xs = ['a', 'b', 'c', 'd']
>>> xs.remove('b')
>>> print(xs)
['a', 'c', 'd']

 

To remove all occurrences of an element, use a list comprehension:

요소의 모든 항목을 제거하려면 리스트 내포를 사용하세요.
>>> xs = ['a', 'b', 'c', 'd', 'b', 'b', 'b', 'b']
>>> xs = [x for x in xs if x != 'b']
>>> print(xs)
['a', 'c', 'd']

 

 

 가장 최근 달린 Solution 

When nums is the list and c is the value to be removed:

nums가 리스트고 c가 제거할 값인 경우:

 

To remove the first occurrence of c in the list, just do:

리스트에서 c의 첫 번째 아이템을 제거하려면 다음을 수행합니다.
if c in nums:
    nums.remove(c)

 

To remove all occurrences of c from the list do:

목록에서 모든 c 항목을 제거하려면 다음을 수행합니다.
while c in nums:
    nums.remove(c)

 

Adding the exception handling would be the best practice, but I mainly wanted to show how to remove all occurrences of an element from the list.

예외 처리를 추가하는 것이 가장 좋은 방법이지만, 저는 주로 리스트에서 요소의 모든 항목을 제거하는 방법을 보여주고 싶었습니다.

 

 

 

출처 : https://stackoverflow.com/questions/2793324/is-there-a-simple-way-to-delete-a-list-element-by-value

반응형