# loops - 在'for'循环中，python 访问索引？

``````
ints = [8, 23, 45, 12, 78]

``````

``````
for idx, val in enumerate(ints):

print(idx, val)

``````

``````
for index, item in enumerate(items):

print(index, item)

``````

``````
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])

``````

of python enumerate 函数通过隐藏索引的会计来减少视觉混乱，并将iterable封装到另一个可迭代的( 一个 enumerate 对象) 中，该( 一个 enumerate 对象) 产生索引的两项元组和原始iterable将提供的项， 这看起来像这样：

``````
for index, item in enumerate(items, start=0): # default is zero

print(index, item)

``````

## 获得计数

``````
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

``````

• python 索引从零开始
• 若要在迭代时从iterable获取这些索引，请使用枚举函数
• 在( 以及元组解包) 中使用枚举方法可以创建更加可读和可维护的代码：

``````
for index, item in enumerate(items, start=0): # Python indexes start at zero

print(index, item)

``````

`1` 以外的 `1` 启动它非常简单:

``````
for index, item in enumerate(iterable, start=1):

print index, item

``````

## 1.使用枚举( 被认为是最常用的)

``````
for index, element in enumerate(lst):

# do the things that need doing here

``````

## 2.创建变量以保存索引( 使用 `for` )

``````
for index in range(len(lst)): # or xrange

# you will have to write extra code to get the element

``````

## 3 。创建变量以保存索引( 使用 `while` )

``````
index = 0

while index <len(lst):

# you will have to write extra code to get the element

index += 1 # escape infinite recursion

``````