sourcetip

for 루프의 Python 루프 카운터

fileupload 2023. 7. 17. 21:22
반응형

for 루프의 Python 루프 카운터

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

이것은 제 문제의 단순화된 예입니다.제 실제 응용 프로그램에서는 그래픽으로 이 작업을 수행하고 각 프레임마다 전체 메뉴를 다시 칠해야 합니다.하지만 이것은 복제하기 쉬운 간단한 텍스트 방식으로 그것을 보여줍니다.

Python 2.5를 사용하고 있다는 것도 추가해야 할 것 같습니다. 2.6 이상에 대한 구체적인 방법이 있는지는 여전히 관심이 있습니다.

# 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

다음과 같이 사용:

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)당신이 원한다면, 하지만 그것들은 외부적이고 일반적으로 포함되지 않습니다.

나는 가끔 이렇게 할 것입니다.

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]두어 번 이상.

다음 작업도 수행할 수 있습니다.

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

중복 옵션이 있으면 문제가 발생할 수 있지만,

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

또한, 그래서 당신은 다음과 같은 것을 할 수 있습니다.

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

반응형