티스토리 뷰

반응형

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

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

 

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

How to find all occurrences of an element in a list

리스트에서 요소의 모든 등장 위치(인덱스) 찾는 방법

 문제 내용 

index() will give the first occurrence of an item in a list. Is there a neat trick which returns all indices in a list for an element?

index() 함수는 리스트에서 항목의 첫 번째 발생을 반환합니다. 하지만 요소에 대한 모든 인덱스를 반환하는 깔끔한 방법은 없을까?

 

 

 

 높은 점수를 받은 Solution 

You can use a list comprehension with enumerate:

리스트 내포를 enumerate와 함께 사용할 수 있습니다:
indices = [i for i, x in enumerate(my_list) if x == "whatever"]

 

The iterator enumerate(my_list) yields pairs (index, item) for each item in the list. Using i, x as loop variable target unpacks these pairs into the index i and the list item x. We filter down to all x that match our criterion, and select the indices i of these elements.

enumerate(my_list) 반복자는 리스트의 각 항목에 대해 쌍(index, item)을 생성합니다. for 루프 변수 대상으로 i, x를 사용하면 이러한 쌍을 인덱스 i와 리스트 항목 x로 분해할 수 있다. 우리는 기준에 부합하는 x를 필터링하고 이러한 요소의 인덱스 i를 선택합니다.

 

 

 

 가장 최근 달린 Solution 

A dynamic list comprehension based solution incase we do not know in advance which element:

미리 어떤 요소를 찾을지 모르는 경우 동적 리스트 내포를 사용할 수 있습니다.
lst = ['to', 'be', 'or', 'not', 'to', 'be']
{req_word: [idx for idx, word in enumerate(lst) if word == req_word] for req_word in set(lst)}

 

results in:

결과는 다음과 같습니다:
{'be': [1, 5], 'or': [2], 'to': [0, 4], 'not': [3]}

 

You can think of all other ways along the same lines as well but with index() you can find only one index although you can set occurrence number yourself.

index()를 사용하여 직접 구현하는 것도 가능하지만, 이 방법은 한 번에 하나의 인덱스만 찾을 수 있습니다.

 

 

 

출처 : https://stackoverflow.com/questions/6294179/how-to-find-all-occurrences-of-an-element-in-a-list

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