Uzyskanie kolejnego elementu podczas przejazdu przez Listę

li = [0, 1, 2, 3]

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

Gdy dojdzie do ostatniego elementu, zostanie podniesiony IndexError (Jak ma to miejsce w przypadku każdej listy, krotki, słownika lub łańcucha iteracyjnego). W tym momencie chcę, aby nextelem było równe li[0]. Moim dość kłopotliwym rozwiązaniem było

while running:
    for elem in li:
        thiselem = elem
        nextelem = li[li.index(elem)-len(li)+1]   # negative index
Czy jest na to lepszy sposób?
Author: igaurav, 2010-01-30

8 answers

Po przemyśleniu tego dokładnie, myślę, że to jest najlepszy sposób. Pozwala łatwo zejść w środku bez użycia break, co moim zdaniem jest ważne i wymaga minimalnej obliczeń, więc myślę, że jest najszybszy. Nie wymaga również, aby li była listą lub krotką. To może być każdy 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)

Zostawiam inne rozwiązania dla potomności.

Wszystkie te fantazyjne Iteratory mają swoje miejsce, ale nie tutaj. Użyj % centrala.

li = [0, 1, 2, 3]

running = True
while running:
    for idx, elem in enumerate(li):
        thiselem = elem
        nextelem = li[(idx + 1) % len(li)]

Teraz, jeśli zamierzasz nieskończenie przechodzić przez Listę, po prostu zrób to:

li = [0, 1, 2, 3]

running = True
idx = 0
while running:
    thiselem = li[idx]
    idx = (idx + 1) % len(li)
    nextelem = li[idx]

Myślę, że jest to łatwiejsze do zrozumienia niż inne rozwiązanie z udziałem tee, i prawdopodobnie szybciej też. Jeśli jesteś pewien, że lista nie zmieni rozmiaru, możesz usunąć kopię len(li) i użyć jej.

To również pozwala łatwo zejść z diabelskiego młyna na środku, zamiast czekać, aż wiadro zejdzie na dno ponownie. Pozostałe rozwiązania (w tym Twój) wymaga sprawdzenia running w środku pętli for, a następnie break.

 58
Author: Omnifarious,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-06-13 13:50:28
while running:
    for elem,next_elem in zip(li, li[1:]+[li[0]]):
        ...
 11
Author: John La Rooy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-01-30 12:35:59

Możesz użyć iteratora cyklicznego:

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)):
    ...
 7
Author: Ants Aasma,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-01-30 12:37:28

Użyj metody zip w Pythonie. Funkcja zwraca listę krotek, gdzie i-ta krotka Zawiera i-ten element z każdej sekwencji argumentów lub iterables

    while running:
        for thiselem,nextelem in zip(li, li[1 : ] + li[ : 1]):
            #Do whatever you want with thiselem and nextelem         
 4
Author: Nirmal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-05-13 06:04:19
while running:
    lenli = len(li)
    for i, elem in enumerate(li):
        thiselem = elem
        nextelem = li[(i+1)%lenli]
 3
Author: Ned Batchelder,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-01-30 13:22:19

Raczej inny sposób na rozwiązanie tego:

   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]
 1
Author: Timothy Dalton,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-07-15 07:30:33
        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)]
 0
Author: Satheesh Alathiyur,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-09-06 11:02:37
c = [ 1, 2, 3, 4 ]

i = int(raw_input(">"))

if i < 4:
    print i + 1
else:
    print -1
 -6
Author: Anurag mishra,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-07-06 19:54:19