programing tip

for 루프의 Python 루프 카운터

itbloger 2020. 6. 23. 07:55
반응형

for 루프의 Python 루프 카운터


이 질문에는 이미 답변이 있습니다.

아래 예제 코드에서 counter = 0이 실제로 필요합니까, 아니면 루프 카운터에 액세스하는 더 나은 Python 방법이 있습니까? 루프 카운터와 관련된 몇 가지 PEP를 보았지만 지연되었거나 거부되었습니다 ( PEP 212PEP 281 ).

이것은 내 문제의 간단한 예입니다. 내 실제 응용 프로그램에서 이것은 그래픽으로 수행되며 전체 메뉴는 각 프레임을 다시 페인트해야합니다. 그러나 이것은 재현하기 쉬운 간단한 텍스트 방식으로 보여줍니다.

아마도 2.6 이상을 사용하는 방법이 여전히 관심이 있지만 Python 2.5를 사용하고 있다고 덧붙일 수도 있습니다.

# Draw all the options, but highlight the selected index
def draw_menu(options, selected_index):
    counter = 0
    for option in options:
        if counter == selected_index:
            print " [*] %s" % option
        else:
            print " [ ] %s" % option
        counter += 1


options = ['Option 0', 'Option 1', 'Option 2', 'Option 3']

draw_menu(option, 2) # Draw menu with "Option2" selected

실행되면 다음을 출력합니다.

 [ ] Option 0
 [ ] Option 1
 [*] Option 2
 [ ] Option 3

다음 enumerate()과 같이 사용하십시오 .

def draw_menu(options, selected_index):
    for counter, option in enumerate(options):
        if counter == selected_index:
            print " [*] %s" % option
        else:
            print " [ ] %s" % option    

options = ['Option 0', 'Option 1', 'Option 2', 'Option 3']
draw_menu(options, 2)

참고 : 원하는 경우과 counter, option같이 괄호를 괄호로 묶을 수 (counter, option)있지만 일반적으로 포함되지는 않습니다.


당신은 또한 할 수 있습니다 :

 for option in options:
      if option == options[selected_index]:
           #print
      else:
           #print

중복 옵션이 있으면 문제가 발생할 수 있습니다.


나는 때때로 이것을 할 것이다 :

def draw_menu(options, selected_index):
    for i in range(len(options)):
        if i == selected_index:
            print " [*] %s" % options[i]
        else:
            print " [ ] %s" % options[i]

나는 이것이 options[i]두 번 이상 말할 것이라고 의미한다면 이것을 피하는 경향이 있지만 .


enumerate 당신이 찾고있는 것입니다.

포장 풀기를 원할 수도 있습니다 .

# The pattern
x, y, z = [1, 2, 3]

# also works in loops:
l = [(28, 'M'), (4, 'a'), (1990, 'r')]
for x, y in l:
    print(x)  # prints the numbers 28, 4, 1990

# and also
for index, (x, y) in enumerate(l):
    print(x)  # prints the numbers 28, 4, 1990

또한, itertools.count()당신이 할 수있는 일이 있습니다.

import itertools

for index, el in zip(itertools.count(), [28, 4, 1990]):
    print(el)  # prints the numbers 28, 4, 1990

참고 URL : https://stackoverflow.com/questions/1185545/python-loop-counter-in-a-for-loop

반응형