How to specify where to start in an itertools.cycle function

前端 未结 3 1340
抹茶落季
抹茶落季 2021-01-12 09:18

I need to cycle through a list for starting position between 1-4 using itertools I am able to cycle through the list

positions = it         


        
3条回答
  •  感情败类
    2021-01-12 10:01

    Use slices of the original list:

    In [15]: def custom_slice(lst, start):
       ....:     return cycle(lst[start:] + lst[:start + 1])
    

    Demo:

    In [16]: positions = custom_slice(lst, 2)
    
    In [17]: next(positions)
    Out[17]: 3
    
    In [18]: next(positions)
    Out[18]: 4
    
    In [19]: next(positions)
    Out[19]: 1
    
    In [20]: next(positions)
    Out[20]: 2
    

提交回复
热议问题