我想在Python中创建一个类似列表的类,但是可以循环地对其进行迭代 用例示例:
myc = SimpleCircle()
print(len(myc))
j = iter(myc)
for i in range (0, 5):
print(next(j))
它将打印 一种 b C d 一个
到目前为止,我尝试过的代码如下
我知道问题出在我的__next__
方法 顺便说一句,它似乎被忽略了,即使我没有实现也可以使用next
class SimpleCircle:
def __init__(self):
self._circle = ['a', 'b', 'c', 'd']
self._l = iter(self._circle)
def __len__(self):
return len(self._circle)
def __iter__(self):
return (elem for elem in self._circle)
def __next__(self):
try:
elem = next(self._l)
idx = self._circle.index(elem)
if idx < len(self._circle):
return elem
else:
return self._circle[0]
except StopIteration:
pass
答案 0 :(得分:2)
这是基本的非itertools实现:
class CyclicIterable:
def __init__(self, data):
self._data = list(data)
def __iter__(self):
while True:
yield from self._data
cycle = CyclicIterable(['a', 'b', 'c', 'd'])
for i, x in zip(range(5), cycle):
print(x)
请注意,由于__next__
类本身就不需要实现Cycle
,就像list
一样,不是迭代器。要使迭代器退出明确地写上:
it = cycle.__iter__()
print(next(it))
print(next(it))
print(next(it))
print(next(it))
print(next(it))
当然,您可以实例化任意多个迭代器。
答案 1 :(得分:1)
itertools.cycle
实际上已经存在,例如:
from itertools import cycle
for x in cycle(['a', 'b', 'c', 'd']):
print(x)
将继续重复该元素。
接下来,您在这里将Iterable和Iterator混合在一起,这些通常是不同的东西。
作为迭代,我们可以继续从self._circle
进行迭代:
class SimpleCircle:
def __init__(self):
self._circle = ['a', 'b', 'c', 'd']
def __len__(self):
return len(self._circle)
def __iter__(self):
if not self._circle:
raise StopIteration
while True:
yield from self._circle
或者对于迭代器:
class CycleIterator:
def __init__(self, iterable):
self.iterator = iter(iterable)
self.__next__ = self._iternext
self.idx = 0
self.list = []
def _iternext(self):
try:
x = next(self.iterator)
self.list.append(x)
return x
except StopIteration:
self.__next__ = self._iterlist
return self._iterlist()
def _iterlist(self):
try:
return self.list[self.index]
except IndexError:
raise StopIteration
finally:
self.index = (self.index + 1) % len(self.list)