Python:循环遍历列表中的元素,到达末尾时反转

Python: cycle through elements in list reversing when the end is reached

我有一个如下所示的列表:

a = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10']

我需要一次循环一个元素,但是当到达列表末尾时,循环需要反转

例如,使用itertools.cycle:

from itertools import cycle
a_cycle = cycle(a)
for _ in range(30):
    print a_cycle.next()

我得到:

01, 02, 03, 04, 05, 06, 07, 08, 09, 10, 01, 02, 03, 04, 05, 06, 07, 08, 09, 10, 01, 02, 03, 04, 05, 06, 07, 08, 09, 10

但我需要的是:

01, 02, 03, 04, 05, 06, 07, 08, 09, 10, 10, 09, 08, 07, 06, 05, 04, 03, 02, 01, 01, 02, 03, 04, 05, 06, 07, 08, 09, 10

我需要循环 a 固定次数,比如 200 次。

您真的需要循环 遍历列表,就像永远向前和向后一样吗?或者只是 .reverse() 列表?

print a + a[::-1]

会按照您的描述去做。 reversed() 内置的也可以工作,但你需要 chain() 它,因为它 returns 是一个迭代器,例如:

print list(itertools.chain(a, reversed(a)))

您可以对任一结果调用 itertools.cycle() 以获得与其反向连接的列表的无限迭代器。

def forwardback(lst):
    tot = len(lst)
    while 1:
        for i in xrange(tot):
            yield lst[i]
        for i in xrange(tot-1,-1,-1):
            yield lst[i]

或(使用cycle的方法,适用于所有迭代器)

def forwardback(lst):
    saved = []
    for elem in lst:
        yield elem
        saved.append(elem)
    while saved:
        for elem in reversed(saved):
            yield elem
        for elem in saved:
            yield elem

您可以cycle the chain of your a and reverseda,例如:

from itertools import cycle, islice, chain

a = range(1, 11)
b = reversed(a)
c = cycle(chain(a, b))
d = list(islice(c, 100)) # `c` is infinite - hence the `islice` to stop at some point...

这给你:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

注意:如果a是可耗尽迭代器,你需要先复制a。但是考虑到你的例子,这会很好。

复制列表 a,反转它,然后附加它。

a = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10']
b = a[:]
b.reverse()
a = a + b

或根据评论建议。

a = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10']
b = a[::-1]
a = a + b