循环通过lis时获取下一个元素

li = [0, 1, 2, 3]

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

当到达最后一个元素时,将引发IndexError(对于任何迭代的列表,元组,字典或字符串都是这种情况)。 我实际上当时希望nextelem等于li[0]。对此,我比较麻烦的解决方案是

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

有更好的方法吗?

igaurav asked 2020-08-06T04:33:52Z
8个解决方案
77 votes

经过仔细考虑之后,我认为这是最好的方法。 它使您无需使用running即可轻松过渡到中间,我认为这很重要,而且所需的计算量最少,因此我认为它是最快的。 它还不需要for为列表或元组。 它可以是任何迭代器。

from itertools import cycle

li = [0, 1, 2, 3]

running = True
licycle = cycle(li)
# Prime the pump
nextelem = next(licycle)
while running:
    thiselem, nextelem = nextelem, next(licycle)

我将其他解决方案留给后代。

所有这些花哨的迭代器内容都有其位置,但不在这里。 使用%运算符。

li = [0, 1, 2, 3]

running = True
while running:
    for idx, elem in enumerate(li):
        thiselem = elem
        nextelem = li[(idx + 1) % len(li)]

现在,如果您打算无限循环浏览列表,则只需执行以下操作:

li = [0, 1, 2, 3]

running = True
idx = 0
while running:
    thiselem = li[idx]
    idx = (idx + 1) % len(li)
    nextelem = li[idx]

我认为这比涉及running的其他解决方案更容易理解,并且可能也更快。 如果您确定列表不会更改大小,则可以松开for的副本并使用它。

这也使您可以轻松地从中间踩下摩天轮,而不必等待铲斗再次下降到底部。 其他解决方案(包括您的解决方案)要求您在for循环的中间检查running,然后再检查break

Omnifarious answered 2020-08-06T04:34:21Z
15 votes
while running:
    for elem,next_elem in zip(li, li[1:]+[li[0]]):
        ...
John La Rooy answered 2020-08-06T04:34:37Z
7 votes

您可以使用成对循环迭代器:

from itertools import izip, cycle, tee

def pairwise(seq):
    a, b = tee(seq)
    next(b)
    return izip(a, b)

for elem, next_elem in pairwise(cycle(li)):
    ...
Ants Aasma answered 2020-08-06T04:34:57Z
5 votes

在Python中使用zip方法。 此函数返回一个元组列表,其中第i个元组包含每个参数序列或可迭代对象中的第i个元素

    while running:
        for thiselem,nextelem in zip(li, li[1 : ] + li[ : 1]):
            #Do whatever you want with thiselem and nextelem         
Nirmal answered 2020-08-06T04:35:19Z
3 votes
while running:
    lenli = len(li)
    for i, elem in enumerate(li):
        thiselem = elem
        nextelem = li[(i+1)%lenli]
Ned Batchelder answered 2020-08-06T04:35:36Z
3 votes

解决此问题的另一种方法:

   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]
Timothy Dalton answered 2020-08-06T04:35:59Z
0 votes
        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)]
Satheesh Alathiyur answered 2020-08-06T04:36:14Z
-7 votes
c = [ 1, 2, 3, 4 ]

i = int(raw_input(">"))

if i < 4:
    print i + 1
else:
    print -1
Anurag mishra answered 2020-08-06T04:36:30Z
translate from https://stackoverflow.com:/questions/2167868/getting-next-element-while-cycling-through-a-list