用于迭代 Python 列表的开始索引

2022-01-24 00:00:00 python iteration

问题描述

在 Python 中迭代列表时设置起始索引的最佳方法是什么.例如,我有一个星期的列表 - 星期日,星期一,星期二,......星期六 - 但我想从星期一开始遍历列表.这样做的最佳做法是什么?

What is the best way to set a start index when iterating a list in Python. For example, I have a list of the days of the week - Sunday, Monday, Tuesday, ... Saturday - but I want to iterate through the list starting at Monday. What is the best practice for doing this?


解决方案

你可以使用 切片:

for item in some_list[2:]:
    # do stuff

这将从第三个元素开始并迭代到最后.

This will start at the third element and iterate to the end.

相关文章