티스토리 뷰

반응형

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

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

 

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

Get unique values from a list in python

파이썬에서 리스트에서 중복되지 않는 값 가져오기

 문제 내용 

I want to get the unique values from the following list:

다음 목록에서 고유한 값만 가져 오려고합니다.
['nowplaying', 'PBS', 'PBS', 'nowplaying', 'job', 'debate', 'thenandnow']

 

The output which I require is:

필요한 출력은 다음과 같습니다.
['nowplaying', 'PBS', 'job', 'debate', 'thenandnow']

 

This code works:

이 코드는 작동합니다.
output = []
for x in trends:
    if x not in output:
        output.append(x)
print(output)

 

is there a better solution I should use?

더 나은 솔루션이 있나요?

 

 

 

 높은 점수를 받은 Solution 

First declare your list properly, separated by commas. You can get the unique values by converting the list to a set.

먼저 쉼표로 구분된 목록을 올바르게 선언하세요. 목록을 세트로 변환하여 고유한 값을 얻을 수 있습니다.
mylist = ['nowplaying', 'PBS', 'PBS', 'nowplaying', 'job', 'debate', 'thenandnow']
myset = set(mylist)
print(myset)

 

If you use it further as a list, you should convert it back to a list by doing:

리스트로 계속 사용하려면 다음을 수행하여 다시 목록으로 변환해야합니다.
mynewlist = list(myset)

 

Another possibility, probably faster would be to use a set from the beginning, instead of a list. Then your code should be:

또 다른 가능성은 더 빠른 것일 수 있습니다. 리스트 대신 처음부터 세트를 사용하는 것입니다. 그런 다음 코드는 다음과 같아야합니다.
output = set()
for x in trends:
    output.add(x)
print(output)

 

As it has been pointed out, sets do not maintain the original order. If you need that, you should look for an ordered set implementation (see this question for more).

이미 언급된 것처럼, set은 원래의 순서를 유지하지 않습니다. 만약 원래의 순서가 필요하다면, 순서를 유지하는 set 구현을 찾아보는 것이 좋습니다. (더 자세한 내용은 이 질문을 참조하세요.)

 

 

 

 가장 최근 달린 Solution 

set can help you filter out the elements from the list that are duplicates. It will work well for str, int or tuple elements, but if your list contains dict or other list elements, then you will end up with TypeError exceptions.

객체의 유일성을 파악하는데 가장 적합한 데이터 구조는 "set"입니다. 이 구조는 str, int 또는 tuple과 같은 요소를 필터링하는 데 잘 작동하지만 목록에 dict 또는 다른 목록 요소가 포함 된 경우 TypeError 예외가 발생합니다.

 

Here is a general order-preserving solution to handle some (not all) non-hashable types:

다음은 일반적인 순서 보존 솔루션 중 일부 (모든 것이 아님)을 처리하기 위한 코드 예시입니다.
def unique_elements(iterable):
    seen = set()
    result = []
    for element in iterable:
        hashed = element
        if isinstance(element, dict):
            hashed = tuple(sorted(element.iteritems()))
        elif isinstance(element, list):
            hashed = tuple(element)
        if hashed not in seen:
            result.append(element)
            seen.add(hashed)
    return result

 

 

출처 : https://stackoverflow.com/questions/12897374/get-unique-values-from-a-list-in-python

반응형
댓글
공지사항
최근에 올라온 글