Start index for iterating Python list

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

提交回复
热议问题