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
有没有更好的方法呢?
Omn*_*ous 78
仔细考虑后,我认为这是最好的方法.它让你在不使用的情况下轻松地在中间退出break,我认为这很重要,并且它需要最少的计算,所以我认为它是最快的.它也不需要li是列表或元组.它可以是任何迭代器.
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]
我认为这比其他涉及的解决方案更容易理解tee,也可能更快.如果你确定列表不会改变大小,你可以松开一份副本len(li)并使用它.
这也让您可以轻松地从中间踩下摩天轮,而不必等待铲斗再次下降到底部.其他解决方案(包括您的解决方案)要求您running在for循环中间检查然后break.
Joh*_*ooy 15
while running:
    for elem,next_elem in zip(li, li[1:]+[li[0]]):
        ...
您可以使用成对循环迭代器:
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)):
    ...
解决这个问题的一种相当不同的方法:
   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]
while running:
    lenli = len(li)
    for i, elem in enumerate(li):
        thiselem = elem
        nextelem = li[(i+1)%lenli]
小智 5
在Python中使用zip方法.此函数返回元组列表,其中第i个元组包含来自每个参数序列或迭代的第i个元素
    while running:
        for thiselem,nextelem in zip(li, li[1 : ] + li[ : 1]):
            #Do whatever you want with thiselem and nextelem         
| 归档时间: | 
 | 
| 查看次数: | 130087 次 | 
| 最近记录: |