티스토리 뷰

반응형

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

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

 

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

Finding the index of an item in a list

리스트에서 아이템의 인덱스 찾기

 문제 내용 

Given a list ["foo", "bar", "baz"] and an item in the list "bar", how do I get its index 1?

리스트 ["foo", "bar", "baz"]와 리스트 "bar"의 아이템이 주어졌을 때,
인덱스 1을 얻으려면 어떻게 해야 합니까?

 

 

 

 높은 점수를 받은 Solution 

>>> ["foo", "bar", "baz"].index("bar")
1

Reference: Data Structures > More on Lists

참조: 데이터 구조 > 목록에 대한 자세한 내용

 

Caveats follow

주의사항은 다음과 같습니다.

 

Note that while this is perhaps the cleanest way to answer the question as asked, index is a rather weak component of the list API, and I can't remember the last time I used it in anger. It's been pointed out to me in the comments that because this answer is heavily referenced, it should be made more complete. Some caveats about list.index follow. It is probably worth initially taking a look at the documentation for it:

이것이 질문에 대답하는 가장 깨끗한 방법일 수 있지만 인덱스는 목록 API의 다소 약한 구성 요소이며, 마지막으로 화가 나서 사용한 것이 언제인지 기억나지 않습니다. 댓글에서 이 답변이 많이 참조되기 때문에 더 완전해야 한다고 지적했습니다. 다음은 list.index에 대한 몇 가지 주의 사항입니다. 처음에는 문서를 검토할 가치가 있을 것입니다.

 

list.index(x[, start[, end]]) 

Return zero-based index in the list of the first item whose value is equal to x. Raises a ValueError if there is no such item.

The optional arguments start and end are interpreted as in the slice notation and are used to limit the search to a particular subsequence of the list. The returned index is computed relative to the beginning of the full sequence rather than the start argument.

list.index(x[, start[, end]) 값이 x와 같은 첫 번째 항목의 목록에서 0 기반 인덱스를 반환합니다. 해당 항목이 없으면 ValueError를 발생시킵니다. 선택적 인수인 start와 end는 슬라이스 표기법과 같이 해석되며 검색을 목록의 특정 시퀀스로 제한하는 데 사용됩니다. 반환된 인덱스는 start 인수가 아닌 전체 시퀀스의 시작을 기준으로 계산됩니다.

 

Linear time-complexity in list length

리스트 길이의 선형 시간 복잡성

 

An index call checks every element of the list in order, until it finds a match. If your list is long, and you don't know roughly where in the list it occurs, this search could become a bottleneck. In that case, you should consider a different data structure. Note that if you know roughly where to find the match, you can give index a hint. For instance, in this snippet, l.index(999_999, 999_990, 1_000_000) is roughly five orders of magnitude faster than straight l.index(999_999), because the former only has to search 10 entries, while the latter searches a million:

인덱스 호출은 일치하는 항목을 찾을 때까지 목록의 모든 요소를 순서대로 검사합니다. 목록이 길고 목록에서 발생하는 위치를 대략적으로 모르는 경우 이 검색이 병목 현상을 일으킬 수 있습니다. 이 경우에는 다른 데이터 구조를 고려해야 합니다. 일치 항목을 찾을 수 있는 위치를 대략적으로 알고 있는 경우 인덱스에 힌트를 줄 수 있습니다. 예를 들어, 이 스니펫에서 l.index(999_999, 999_999, 1_000_000)는 직선 l.index(999_999)보다 대략 5배 더 빠르다.

 

>>> import timeit
>>> timeit.timeit('l.index(999_999)', setup='l = list(range(0, 1_000_000))', number=1000)
9.356267921015387
>>> timeit.timeit('l.index(999_999, 999_990, 1_000_000)', setup='l = list(range(0, 1_000_000))', number=1000)
0.0004404920036904514
 

Only returns the index of the first match to its argument

첫 번째 일치의 인덱스만 인수로 반환합니다.

 

A call to index searches through the list in order until it finds a match, and stops there. If you expect to need indices of more matches, you should use a list comprehension, or generator expression.

인덱스 호출은 일치하는 항목을 찾을 때까지 목록을 검색한 후 중지됩니다. 더 많은 일치 항목의 인덱스가 필요한 경우 목록 이해 또는 생성자 식을 사용해야 합니다.

 

>>> [1, 1].index(1)
0
>>> [i for i, e in enumerate([1, 2, 1]) if e == 1]
[0, 2]
>>> g = (i for i, e in enumerate([1, 2, 1]) if e == 1)
>>> next(g)
0
>>> next(g)
2

Most places where I once would have used index, I now use a list comprehension or generator expression because they're more generalizable. So if you're considering reaching for index, take a look at these excellent Python features.

예전에는 색인을 사용했을 대부분의 위치에서 목록 이해 또는 생성자 표현식을 사용합니다. 목록 이해 또는 생성자 표현식이 더 일반화되기 때문입니다. 따라서 인덱스에 접근할 생각이라면 다음과 같은 훌륭한 Python 기능을 살펴보십시오.

 

Throws if element not present in list

요소가 목록에 없는 경우 슬로우합니다.

 

A call to index results in a ValueError if the item's not present.

index를 호출하고 항목이 없으면 ValueError가 발생합니다.
>>> [1, 1].index(2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: 2 is not in list

 

If the item might not be present in the list, you should either

항목이 목록에 없을 수도 있는 경우 다음 중 하나를 수행해야 합니다.

 

  1. Check for it first with item in my_list (clean, readable approach), or
  2. Wrap the index call in a try/except block which catches ValueError (probably faster, at least when the list to search is long, and the item is usually present.)
1. my_list 항목(깨끗하고 읽기 쉬운 접근법)으로 먼저 확인하거나
2. ValueError를 포착하는 시도/제외 블록으로 인덱스 호출을 래핑합니다(적어도 검색할 목록이 길고 항목이 일반적으로 있을 때 더 빠를 수 있습니다).

 

 

 

 가장 최근 달린 Solution 

Try the following code:

다음 코드를 사용해 보십시오.
["foo", "bar", "baz"].index("bar")

 

Refer to: https://www.programiz.com/python-programming/methods/list/index

https://www.programiz.com/python-programming/methods/list/index을 참조하십시오.

 

 

 

출처 : https://stackoverflow.com/questions/176918/finding-the-index-of-an-item-in-a-list

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