Getting next element while cycling through a list

2019-01-30 14:52发布

li = [0, 1, 2, 3]

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

When this reaches the last element, an IndexError is raised (as is the case for any list, tuple, dictionary, or string that is iterated). I actually want at that point for nextelem to equal li[0]. My rather cumbersome solution to this was

while running:
    for elem in li:
        thiselem = elem
        nextelem = li[li.index(elem)-len(li)+1]   # negative index

Is there a better way of doing this?

8条回答
趁早两清
2楼-- · 2019-01-30 15:34
c = [ 1, 2, 3, 4 ]

i = int(raw_input(">"))

if i < 4:
    print i + 1
else:
    print -1
查看更多
放荡不羁爱自由
3楼-- · 2019-01-30 15:35
while running:
    lenli = len(li)
    for i, elem in enumerate(li):
        thiselem = elem
        nextelem = li[(i+1)%lenli]
查看更多
登录 后发表回答