Start index for iterating Python list

前端 未结 8 1922
走了就别回头了
走了就别回头了 2020-12-23 02:52

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

相关标签:
8条回答
  • 2020-12-23 03:33

    You can use slicing:

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

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

    0 讨论(0)
  • 2020-12-23 03:36

    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.

    >>> def rotated_sequence(seq, start_index):
    ...     n = len(seq)
    ...     for i in xrange(n):
    ...         yield seq[(i + start_index) % n]
    ...
    >>> s = 'su m tu w th f sa'.split()
    >>> list(rotated_sequence(s, s.index('m')))
    ['m', 'tu', 'w', 'th', 'f', 'sa', 'su']
    >>>
    
    0 讨论(0)
提交回复
热议问题