li = [0, 1, 2, 3]
running = True
while running:
for elem in li:
thiselem = elem
nextelem = li[li.index(elem)+1]
当它到达最后一个元素时,IndexError
会引发 an(对于任何迭代的列表、元组、字典或字符串都是如此)。那时我实际上想要 for nextelem
to equal li[0]
。我对此相当麻烦的解决方案是
while running:
for elem in li:
thiselem = elem
nextelem = li[li.index(elem)-len(li)+1] # negative index
有没有更好的方法来做到这一点?