Getting next element while cycling through a list

前端 未结 12 918
暖寄归人
暖寄归人 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:14
       while running:
            lenli = len(li)
            for i, elem in enumerate(li):
                thiselem = elem
                nextelem = li[(i+1)%lenli] # This line is vital
    
    0 讨论(0)
  • 2020-12-23 00:18

    As simple as this:

    li = [0, 1, 2, 3]
    while 1:
       for i, item in enumerate(x):
          k = i + 1 if i != len(x) - 1 else 0
          print('Current index {} : {}'.format(i,li[k]))
    
    0 讨论(0)
  • 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]
    
    0 讨论(0)
  • 2020-12-23 00:28
            li = [0, 1, 2, 3]
            for elem in li:
                if (li.index(elem))+1 != len(li):
                    thiselem = elem
                    nextelem = li[li.index(elem)+1]
                    print 'thiselem',thiselem
                    print 'nextel',nextelem
                else:
                    print 'thiselem',li[li.index(elem)]
                    print 'nextel',li[li.index(elem)]
    
    0 讨论(0)
  • 2020-12-23 00:30
    while running:
        lenli = len(li)
        for i, elem in enumerate(li):
            thiselem = elem
            nextelem = li[(i+1)%lenli]
    
    0 讨论(0)
  • 2020-12-23 00:30

    The simple solution is to remove IndexError by incorporating the condition:

    if(index<(len(li)-1))
    

    The error 'index out of range' will not occur now as the last index will not be reached. The idea is to access the next element while iterating. On reaching the penultimate element, you can access the last element.

    Use enumerate method to add index or counter to an iterable(list, tuple, etc.). Now using the index+1, we can access the next element while iterating through the list.

    li = [0, 1, 2, 3]
    
    running = True
    while running:
        for index, elem in enumerate(li):
            if(index<(len(li)-1)):
                thiselem = elem
                nextelem = li[index+1]
    
    0 讨论(0)
提交回复
热议问题