在“for”循环中访问索引

新手上路,请多包涵

如何在使用 for 循环迭代序列时访问索引?

 xs = [8, 23, 45]

for x in xs:
    print("item #{} = {}".format(index, x))

期望的输出:

 item #1 = 8
item #2 = 23
item #3 = 45

原文由 Joan Venge 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 636
2 个回答

使用内置函数 enumerate()

 for idx, x in enumerate(xs):
    print(idx, x)

通过 for i in range(len(xs)): x = xs[i] 手动索引或手动管理其他状态变量 是非 Pythonic。

查看 PEP 279 了解更多信息。

原文由 Mike Hordecki 发布,翻译遵循 CC BY-SA 4.0 许可协议

使用 for 循环,如何访问循环索引,在这种情况下是从 1 到 5?

使用 enumerate 在迭代时获取元素的索引:

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

并注意 Python 的索引从零开始,所以你会得到 0 到 4 以上。如果你想要计数,1 到 5,这样做:

 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)

单向控制流

您所要求的是以下的 Pythonic 等价物,这是大多数低级语言程序员会使用的算法:

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

或者在没有 for-each 循环的语言中:

> ```
>  index = 0
> while index < len(items):
>     print(index, items[index])
>     index += 1
>
> ```

或者有时在 Python 中更常见(但不合常理):

> ```
>  for index in range(len(items)):
>     print(index, items[index])
>
> ```

# 使用枚举函数

Python 的 [`enumerate` 函数](https://docs.python.org/2/library/functions.html#enumerate) 通过隐藏索引的计算来减少视觉混乱,并将可迭代对象封装到另一个可迭代对象( `enumerate` 对象)中,该对象产生索引的两项元组和原始可迭代对象将提供的项目。看起来像这样:

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


该代码示例是典型的 Python 惯用代码与非 Python 惯用代码之间区别的 [典型](http://python.net/%7Egoodger/projects/pycon/2007/idiomatic/handout.html#index-item-2-enumerate) 示例。惯用代码是复杂(但不复杂)的 Python,以其预期使用的方式编写。惯用代码是语言设计者所期望的,这意味着通常这种代码不仅更具可读性,而且更高效。

## 计数

即使您不需要索引,但您需要迭代计数(有时需要),您可以从 `1` 开始,最终数字将是您的计数。

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


当你说你想要从 1 到 5 时,计数似乎更多的是你打算要求的(而不是索引)。

* * *

## 分解它——一步一步的解释

为了分解这些示例,假设我们有一个要使用索引迭代的项目列表:

items = [‘a’, ‘b’, ‘c’, ’d’, ‘e’]


现在我们将这个可迭代传递给枚举,创建一个枚举对象:

enumerate_object = enumerate(items) # the enumerate object


我们可以使用 `next` 函数从这个可迭代对象中拉出第一个项目:

iteration = next(enumerate_object) # first iteration from enumerate print(iteration)


我们看到我们得到了 `0` 的元组,第一个索引,以及 `'a'` ,第一个项目:

(0, ‘a’)


我们可以使用所谓的“ [序列拆包](https://docs.python.org/2/tutorial/datastructures.html#tuples-and-sequences)”从这个二元组中提取元素:

index, item = iteration

0, ‘a’ = (0, ‘a’) # essentially this.


当我们检查 `index` 时,我们发现它指的是第一个索引 0,而 `item` 指的是第一个项目 `'a'`

print(index) 0 print(item) a


# 结论

- Python 索引从零开始
- 要在迭代时从可迭代对象中获取这些索引,请使用枚举函数
- 以惯用的方式使用 enumerate(连同元组解包)可以创建更具可读性和可维护性的代码:

所以这样做:

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

”`

原文由 Russia Must Remove Putin 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题