python - Accédez à l'index en 39;pour bloquer#39

Mots clés : pythonloopslistpython

meilleur 5 Réponses python - Accédez à l'index en 39;pour bloquer#39

vote vote

97

for idx, val in enumerate(ints):     print(idx, val) 
vote vote

87

for index, item in enumerate(items):     print(index, item) 
count = 0 # in case items is empty and you need it after the loop for count, item in enumerate(items, start=1):     print(count, item) 
index = 0            # Python's indexing starts at zero for item in items:   # Python's for loops are a "for each" loop      print(index, item)     index += 1 
index = 0 while index < len(items):     print(index, items[index])     index += 1 
for index in range(len(items)):     print(index, items[index]) 
for index, item in enumerate(items, start=0):   # default is zero     print(index, item) 
count = 0 # in case items is empty for count, item in enumerate(items, start=1):   # default is zero     print(item)  print('there were {0} items printed'.format(count)) 
items = ['a', 'b', 'c', 'd', 'e'] 
enumerate_object = enumerate(items) # the enumerate object 
iteration = next(enumerate_object) # first iteration from enumerate print(iteration) 
(0, 'a') 
index, item = iteration #   0,  'a' = (0, 'a') # essentially this. 
>>> print(index) 0 >>> print(item) a 
for index, item in enumerate(items, start=0):   # Python indexes start at zero     print(index, item) 
vote vote

72

for index, item in enumerate(iterable, start=1):    print index, item  # Used to print in python<3.x    print(index, item) # Mirate print() after 3.x+     
vote vote

69

for i in range(len(ints)):    print(i, ints[i]) # print updated to print() in Python 3.x+  
vote vote

56

for index, element in enumerate(lst):     # do the things that need doing here 
for index in range(len(lst)):   # or xrange     # you will have to write extra code to get the element 
index = 0 while index < len(lst):     # you will have to write extra code to get the element     index += 1  # escape infinite recursion 

Questions similaires