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
有没有更好的方法呢?
仔细考虑后,我认为这是最好的方法。它可以让你轻松地在中间离开而不使用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
。
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)):
...
在Python中使用zip方法。此函数返回元组列表,其中第i个元组包含来自每个参数序列或迭代的第i个元素
while running:
for thiselem,nextelem in zip(li, li[1 : ] + li[ : 1]):
#Do whatever you want with thiselem and nextelem
while running:
lenli = len(li)
for i, elem in enumerate(li):
thiselem = elem
nextelem = li[(i+1)%lenli]
一种相当不同的解决方法:
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]
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)]
c = [ 1, 2, 3, 4 ]
i = int(raw_input(">"))
if i < 4:
print i + 1
else:
print -1