循环遍历列表时获取下一个元素
问题:循环遍历列表时获取下一个元素 li = [0, 1, 2, 3] running = True while running: for elem in li: thiselem = elem nextelem = li[li.index(elem)+1] 当它到达最后一个元素时,会引发IndexError(对于任何迭代的列表、元组、字典或字符串都是如此)。我实际上希望nextelem等于li[
·
问题:循环遍历列表时获取下一个元素
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)
的副本存储起来并使用它。
这也让您可以轻松地从中间的摩天轮上下来,而不必等待水桶再次落到底部。其他解决方案(包括您的)要求您在for
循环中间检查running
,然后检查break
。
更多推荐
目录
所有评论(0)