Getting next element while cycling through a list

前端 未结 12 969
暖寄归人
暖寄归人 2020-12-22 23:48
li = [0, 1, 2, 3]

running = True
while running:
    for elem in li:
        thiselem = elem
        nextelem = li[li.index(elem)+1]

When this reac

12条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-23 00:25

    A rather different way to solve this:

       li = [0,1,2,3]
    
       for i in range(len(li)):
    
           if i < len(li)-1:
    
               # until end is reached
               print 'this', li[i]
               print 'next', li[i+1]
    
           else:
    
               # end
               print 'this', li[i]
    

提交回复
热议问题