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中有一个方法可以做到这一点吗?
您可以编写自己的类来模拟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)
您可以使用deque
fromcollections
模块和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)