itertools'previous'(下一个)python

Chr*_*ris 6 python python-itertools python-3.x

我目前正在使用类似的东西

>> import itertools
>> ABC = [a, b, c]
>> abc = itertools.cycle( ABC )
>> next( abc )
a
>> next( abc )
b    
>> next( abc )
c
Run Code Online (Sandbox Code Playgroud)

我希望我的下一个电话是

>> previous( abc )
b
Run Code Online (Sandbox Code Playgroud)

itertools中有一个方法可以做到这一点吗?

ric*_*ici 5

不,没有.

由于Python的迭代协议的工作方式,如果previous不保留生成的值的整个历史记录就不可能实现.Python不会这样做,并且考虑到你可能不希望它的内存要求.


Sad*_*deh 5

您可以编写自己的类来模拟iterable具有 next 和 previous 的对象。这是最简单的实现:

class cycle:
    def __init__(self, c):
        self._c = c
        self._index = -1

    def __next__(self):
        self._index += 1
        if self._index>=len(self._c):
            self._index = 0
        return self._c[self._index]

    def previous(self):
        self._index -= 1
        if self._index < 0:
            self._index = len(self._c)-1
        return self._c[self._index]

ABC = ['a', 'b', 'c']
abc = cycle(ABC)
print(next(abc))
print(next(abc))
print(next(abc))
print(abc.previous())
Run Code Online (Sandbox Code Playgroud)


Lyn*_*ynx 5

您可以使用dequefromcollections模块和rotate方法,例如:

from collections import deque

alist=['a','b','c']
d=deque(alist)

current = d[0] 
print(current) # 'a'

d.rotate(1) # rotate one step to the right
current = d[0] 
print(current) # 'c'

d.rotate(-1) # rotate one step to the left
current = d[0] 
print(current) # 'a' again
Run Code Online (Sandbox Code Playgroud)