python - 是否有内置的 python 方法使用索引值而不是元素遍历列表

标签 python list

我正在寻找一种使用索引值而不是实际元素本身遍历列表的 python 方法。代码正是这样做的:

for index in range(len(list)-1):
    # do stuff

我正在查看是否已经有执行此操作的函数,或者我是否应该自己添加它。

最佳答案

使用枚举:

for index, ignore_this_its_the_value in enumerate(list):
   # do stuff

但实际上:

for index in range(len(list)):
   # do stuff

确实会产生适当的索引。

关于python - 是否有内置的 python 方法使用索引值而不是元素遍历列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37199448/

相关文章:

python - 设计推荐 : control flow based on argument type in Python?

python - 沿着 Pandas Dataframe 中的列进行计数?

python - 在 heroku 上部署时运行一次 python 脚本

python - 如何有效地统计Python列表中的共现情况

python - 使用键和值列表到字典

python - modwsgi 和 mysql。查询仅显示触及 wsgi 文件后的实际结果

python - Python 分隔连续字符串

r - 从数据帧列表中获取名称与 id 连接的向量

python - 检查列表是否只包含项目 x

python - 在 python 3 中通过使用算术和逻辑运算符保留某些单词来标记单词?