반응형
for 루프의 Python 루프 카운터
이 질문에는 이미 답변이 있습니다.
- 'for'루프에서 인덱스에 액세스합니까? 답변 19 개
아래 예제 코드에서 counter = 0이 실제로 필요합니까, 아니면 루프 카운터에 액세스하는 더 나은 Python 방법이 있습니까? 루프 카운터와 관련된 몇 가지 PEP를 보았지만 지연되었거나 거부되었습니다 ( PEP 212 및 PEP 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
반응형
'programing tip' 카테고리의 다른 글
multiprocessing.Process에 전달 된 함수의 반환 값을 어떻게 복구 할 수 있습니까? (0) | 2020.06.23 |
---|---|
Visual Studio 2017에서 세로 점선 들여 쓰기 줄 제거 (0) | 2020.06.23 |
Git을 사용하면“LF는 CRLF로 대체됩니다”경고를 끄려면 어떻게합니까 (0) | 2020.06.23 |
LINQ To 엔터티는 마지막 방법을 인식하지 못합니다. (0) | 2020.06.23 |
postgresql에서 여러 열을 삭제하는 방법 (0) | 2020.06.23 |