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?
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
Here's a rotation generator which doesn't need to make a warped copy of the input sequence ... may be useful if the input sequence is much larger than 7 items.
If all you want is to print from
Monday
onwards, you can uselist
'sindex
method to find the position where "Monday" is in the list, and iterate from there as explained in other posts. Usinglist.index
saves you hard-coding the index for "Monday", which is a potential source of error:You can use slicing:
This will start at the third element and iterate to the end.
stdlib will hook you up son!
deque.rotate()
:You can always loop using an index counter the conventional C style looping:
It is always better to follow the "loop on every element" style because that's the normal thing to do, but if it gets in your way, just remember the conventional style is also supported, always.
If you want to "wrap around" and effectively rotate the list to start with Monday (rather than just chop off the items prior to Monday):