티스토리 뷰

개발/파이썬

'for' 루프의 인덱스 접근

맨날치킨 2022. 11. 29. 08:05
반응형

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

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

 

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

Accessing the index in 'for' loops

'for' 루프의 인덱스 접근

 문제 내용 

How do I access the index while iterating over a sequence with a for loop?

for 루프가 있는 시퀀스를 반복하는 동안 인덱스에 액세스하려면 어떻게 해야 합니까?

 

xs = [8, 23, 45]

for x in xs:
    print("item #{} = {}".format(index, x))

Desired output:

원하는 출력:

 

item #1 = 8
item #2 = 23
item #3 = 45

 

 

 높은 점수를 받은 Solution 

Use the built-in function enumerate():

내장 함수인 enumerate() 사용:
for idx, x in enumerate(xs):
    print(idx, x)

 

It is non-pythonic to manually index via for i in range(len(xs)): x = xs[i] or manually manage an additional state variable.

fori in range(len(len): x = xs[i]를 통해 수동으로 인덱싱하거나 추가 상태 변수를 수동으로 관리하는 것은 파이썬스럽지 않습니다.

 

Check out PEP 279 for more.

자세한 내용은 PEP 279를 참조하십시오.

 

 

 

 가장 최근 달린 Solution 

In addition to all the excellent answers above, here is a solution to this problem when working with pandas Series objects. In many cases, pandas Series have custom/unique indices (for example, unique identifier strings) that can't be accessed with the enumerate() function.

위의 모든 우수한 답변 외에도 다음은 pandas 시리즈 개체로 작업할 때 발생하는 이 문제에 대한 해결책입니다. 대부분의 경우 pandas 시리즈에는 enumerate() 함수로 액세스할 수 없는 사용자 지정/고유 인덱스(예: 고유 식별자 문자열)가 있습니다.

 

xs = pd.Series([8, 23, 45])  xs.index = ['G923002', 'G923004', 'G923005']  print(xs) 

Output:

#    G923002     8 #    G923004    23 #    G923005    45 #    dtype: int64 

 

We can see below that enumerate() doesn't give us the desired result:

아래에서 enumery()가 원하는 결과를 제공하지 않음을 알 수 있습니다.

 

for id, x in enumerate(xs):     
	print("id #{} = {}".format(id, x))

Output:

#    id #0 = 8 
#    id #1 = 23 
#    id #2 = 45

 

We can access the indices of a pandas Series in a for loop using .items():

.items()를 사용하여 for 루프의 pandas 시리즈 인덱스에 액세스할 수 있습니다.

 

for id, x in xs.items():     
	print("id #{} = {}".format(id, x))

Output:

#    id #G923002 = 8 
#    id #G923004 = 23 
#    id #G923005 = 45

 

 

 

출처 : https://stackoverflow.com/questions/522563/accessing-the-index-in-for-loops

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