Licznik pętli Pythona w pętli for

W poniższym przykładzie, czy counter = 0 jest naprawdę wymagany, czy jest lepszy, bardziej Pythonowy sposób na uzyskanie dostępu do licznika pętli? Widziałem kilka Pepów związanych z licznikami pętli, ale były albo odroczone, albo odrzucone (PEP 212 i PEP 281 ).

To uproszczony przykład mojego problemu. W mojej prawdziwej aplikacji odbywa się to z grafiką i całe menu musi być przemalowane każdą klatkę. Ale to pokazuje to w prosty tekstowy sposób, który jest łatwy do rozmnażać.

Może powinienem też dodać, że używam Pythona 2.5, chociaż nadal jestem zainteresowany, czy istnieje sposób specyficzny dla 2.6 lub wyższej.

# 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

Po uruchomieniu wyświetla:

 [ ] Option 0
 [ ] Option 1
 [*] Option 2
 [ ] Option 3
Author: Andre Miller, 2009-07-27

4 answers

Użycie enumerate() jak tak:

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)

Uwaga: możesz opcjonalnie umieścić nawias wokół counter, option, Jak (counter, option), Jeśli chcesz, ale są one obce i zwykle nie są uwzględniane.

 226
Author: Evan Fosmark,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-10-15 18:29:26

Można też zrobić:

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

Chociaż napotkasz problemy, jeśli istnieją zduplikowane opcje.

 4
Author: thedz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-07-26 21:11:08

Czasami to zrobię:

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]
Chociaż staram się tego unikać, jeśli to oznacza, że będę mówił więcej niż kilka razy.
 4
Author: Laurence Gonsalves,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-07-26 21:28:17

enumerate to jest to, czego szukasz.

Możesz być również zainteresowany rozpakowywanie :

# 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

Jest też itertools.count() więc możesz zrobić coś w stylu

import itertools

for index, el in zip(itertools.count(), [28, 4, 1990]):
    print(el)  # prints the numbers 28, 4, 1990
 1
Author: Martin Thoma,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-09-10 14:43:10