Start index for iterating Python list

前端 未结 8 1921
走了就别回头了
走了就别回头了 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:11

    stdlib will hook you up son!

    deque.rotate():

    #!/usr/local/bin/python2.7
    
    from collections import deque
    
    a = deque('Monday Tuesday Wednesday Thursday Friday Saturday Sunday'.split(' '))
    a.rotate(3)
    deque(['Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday'])
    
    0 讨论(0)
  • 2020-12-23 03:12

    You can always loop using an index counter the conventional C style looping:

    for i in range(len(l)-1):
        print l[i+1]
    

    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.

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

    If all you want is to print from Monday onwards, you can use list's index method to find the position where "Monday" is in the list, and iterate from there as explained in other posts. Using list.index saves you hard-coding the index for "Monday", which is a potential source of error:

    days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
    for d in days[days.index('Monday'):] :
       print d
    
    0 讨论(0)
  • 2020-12-23 03:20

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

    dayNames = [ 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 
                'Friday', 'Saturday',  ]
    
    startDayName = 'Monday'
    
    startIndex = dayNames.index( startDayName )
    print ( startIndex )
    
    rotatedDayNames = dayNames[ startIndex: ] + dayNames [ :startIndex ]
    
    for x in rotatedDayNames:
        print ( x )
    
    0 讨论(0)
  • 2020-12-23 03:29

    Why are people using list slicing (slow because it copies to a new list), importing a library function, or trying to rotate an array for this?

    Use a normal for-loop with range(start, stop, step) (where start and step are optional arguments).

    For example, looping through an array starting at index 1:

    for i in range(1, len(arr)):
        print(arr[i])
    
    0 讨论(0)
  • 2020-12-23 03:31

    islice has the advantage that it doesn't need to copy part of the list

    from itertools import islice
    for day in islice(days, 1, None):
        ...
    
    0 讨论(0)
提交回复
热议问题