循环列表时获取下一个元素

发布于 2024-08-20 01:21:28 字数 465 浏览 4 评论 0原文

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

有更好的方法吗?

li = [0, 1, 2, 3]

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

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

Is there a better way of doing this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(12

仔细想了想,我觉得这是最好的办法。它可以让你在不使用 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

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]

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.

み格子的夏天 2024-08-27 01:21:28
while running:
    for elem,next_elem in zip(li, li[1:]+[li[0]]):
        ...
while running:
    for elem,next_elem in zip(li, li[1:]+[li[0]]):
        ...
空宴 2024-08-27 01:21:28

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

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)):
    ...

You can use a pairwise cyclic iterator:

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)):
    ...
空气里的味道 2024-08-27 01:21:28
while running:
    lenli = len(li)
    for i, elem in enumerate(li):
        thiselem = elem
        nextelem = li[(i+1)%lenli]
while running:
    lenli = len(li)
    for i, elem in enumerate(li):
        thiselem = elem
        nextelem = li[(i+1)%lenli]
岁月无声 2024-08-27 01:21:28

解决这个问题的一种相当不同的方法:

   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]

A rather different way to solve this:

   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]
最好是你 2024-08-27 01:21:28

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

    while running:
        for thiselem,nextelem in zip(li, li[1 : ] + li[ : 1]):
            #Do whatever you want with thiselem and nextelem         

Use the zip method in Python. This function returns a list of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables

    while running:
        for thiselem,nextelem in zip(li, li[1 : ] + li[ : 1]):
            #Do whatever you want with thiselem and nextelem         
ゞ记忆︶ㄣ 2024-08-27 01:21:28

就这么简单:

li = [0, 1, 2, 3]
while 1:
   for i, item in enumerate(x):
      k = i + 1 if i != len(x) - 1 else 0
      print('Current index {} : {}'.format(i,li[k]))

As simple as this:

li = [0, 1, 2, 3]
while 1:
   for i, item in enumerate(x):
      k = i + 1 if i != len(x) - 1 else 0
      print('Current index {} : {}'.format(i,li[k]))
や莫失莫忘 2024-08-27 01:21:28

简单的解决方案是通过合并以下条件来删除 IndexError:

if(index<(len(li)-1))

由于无法到达最后一个索引,因此现在不会发生错误“索引超出范围”。这个想法是在迭代时访问下一个元素。到达倒数第二个元素后,您可以访问最后一个元素。

使用枚举方法向可迭代对象(列表、元组等)添加索引或计数器。现在使用索引+1,我们可以在迭代列表时访问下一个元素。

li = [0, 1, 2, 3]

running = True
while running:
    for index, elem in enumerate(li):
        if(index<(len(li)-1)):
            thiselem = elem
            nextelem = li[index+1]

The simple solution is to remove IndexError by incorporating the condition:

if(index<(len(li)-1))

The error 'index out of range' will not occur now as the last index will not be reached. The idea is to access the next element while iterating. On reaching the penultimate element, you can access the last element.

Use enumerate method to add index or counter to an iterable(list, tuple, etc.). Now using the index+1, we can access the next element while iterating through the list.

li = [0, 1, 2, 3]

running = True
while running:
    for index, elem in enumerate(li):
        if(index<(len(li)-1)):
            thiselem = elem
            nextelem = li[index+1]
风向决定发型 2024-08-27 01:21:28
        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)]
        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)]
卷耳 2024-08-27 01:21:28
   while running:
        lenli = len(li)
        for i, elem in enumerate(li):
            thiselem = elem
            nextelem = li[(i+1)%lenli] # This line is vital
   while running:
        lenli = len(li)
        for i, elem in enumerate(li):
            thiselem = elem
            nextelem = li[(i+1)%lenli] # This line is vital
青衫儰鉨ミ守葔 2024-08-27 01:21:28

我使用枚举来处理这个问题。

storage = ''
for num, value in enumerate(result, start=0):
    content = value
    if 'A' == content:
        storage = result[num + 1]

我在这里使用 num 作为索引,当它找到正确的值时,它会将实际列表的当前索引加一。这使我能够转向下一个索引。

我希望这对您的目的有所帮助。

I've used enumeration to handle this problem.

storage = ''
for num, value in enumerate(result, start=0):
    content = value
    if 'A' == content:
        storage = result[num + 1]

I've used num as Index here, when it finds the correct value it adds up one to the current index of actual list. Which allows me to maneuver to the next index.

I hope this helps your purpose.

七婞 2024-08-27 01:21:28

对于字符串列表,从 1(或任何> 0)直到结束。

itens = ['car', 'house', 'moon', 'sun']

v = 0
for item in itens:
    b = itens[1 + v]
    print(b)
    print('any other command')
    if b == itens[-1]:
        print('End')
        break
    v += 1

For strings list from 1(or whatever > 0) until end.

itens = ['car', 'house', 'moon', 'sun']

v = 0
for item in itens:
    b = itens[1 + v]
    print(b)
    print('any other command')
    if b == itens[-1]:
        print('End')
        break
    v += 1
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文