在列表中循环时获取下一个元素 [英] Getting next element while cycling through a list
问题描述
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]
。我的相当麻烦的解决方案是
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
有更好的方法吗?
推荐答案
仔细思考后,我认为这是最好的办法。它允许你轻松地在中间退出而不使用 break
,我认为这很重要,并且它需要最少的计算,所以我认为它是最快的。它也不要求 li
是一个列表或元组。它可以是任何迭代器。
After thinking this through carefully, I think this is the best way. It lets you step off in the middle easily without using break
, which I think is important, and it requires minimal computation, so I think it's the fastest. It also doesn't require that li
be a list or tuple. It could be any iterator.
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)
我将其他解决方案留给后人。
I'm leaving the other solutions here for posterity.
所有那些花哨的迭代器都有它的位置,但不是这里。使用%运算符。
All of that fancy iterator stuff has its place, but not here. Use the % operator.
li = [0, 1, 2, 3]
running = True
while running:
for idx, elem in enumerate(li):
thiselem = elem
nextelem = li[(idx + 1) % len(li)]
现在,如果您打算无限循环浏览列表,那么就这样做:
Now, if you intend to infinitely cycle through a list, then just do this:
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)
的副本并使用它。
I think that's easier to understand than the other solution involving tee
, and probably faster too. If you're sure the list won't change size, you can squirrel away a copy of len(li)
and use that.
这也让你可以轻松地从中间踩下摩天轮而不必等待铲斗再次下降到底部。其他解决方案(包括您的解决方案)要求您在中间
循环中检查运行
然后中断
。
This also lets you easily step off the ferris wheel in the middle instead of having to wait for the bucket to come down to the bottom again. The other solutions (including yours) require you check running
in the middle of the for
loop and then break
.
这篇关于在列表中循环时获取下一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!