Как сделать итератор python назад?
В любом случае, чтобы итератор списка python мог вернуться назад?
В основном у меня это
class IterTest(object):
def __init__(self, data):
self.data = data
self.__iter = None
def all(self):
self.__iter = iter(self.data)
for each in self.__iter:
mtd = getattr(self, type(each).__name__)
mtd(each)
def str(self, item):
print item
next = self.__iter.next()
while isinstance(next, int):
print next
next = self.__iter.next()
def int(self, item):
print "Crap i skipped C"
if __name__ == '__main__':
test = IterTest(['a', 1, 2,3,'c', 17])
test.all()
Запуск этого кода приводит к выводу:
a
1
2
3
Crap i skipped C
Я знаю, почему он дает мне вывод, однако есть ли способ, которым я могу шагнуть назад в методе str(), одним шагом?
ИЗМЕНИТЬ
Хорошо, возможно, чтобы это стало яснее. Я не хочу делать полный оборот, в основном, что я хочу знать, есть ли простой способ сделать эквивалент итератора двунаправленного в python?
Ответы
Ответ 1
Нет, в общем, вы не можете сделать итератор Python назад. Однако, если вы хотите только один раз отступить, вы можете попробовать что-то вроде этого:
def str(self, item):
print item
prev, current = None, self.__iter.next()
while isinstance(current, int):
print current
prev, current = current, self.__iter.next()
Затем вы можете получить доступ к предыдущему элементу в prev
.
Если вам действительно нужен двунаправленный итератор, вы можете реализовать его самостоятельно, но он, скорее всего, принесет еще больше накладных расходов, чем решение выше:
class bidirectional_iterator(object):
def __init__(self, collection):
self.collection = collection
self.index = 0
def next(self):
try:
result = self.collection[self.index]
self.index += 1
except IndexError:
raise StopIteration
return result
def prev(self):
self.index -= 1
if self.index < 0:
raise StopIteration
return self.collection[self.index]
def __iter__(self):
return self
Ответ 2
Я что-то упустил или вы не можете использовать технику, описанную в разделе "Итератор" в руководстве по Python?
>>> class reverse_iterator:
... def __init__(self, collection):
... self.data = collection
... self.index = len(self.data)
... def __iter__(self):
... return self
... def next(self):
... if self.index == 0:
... raise StopIteration
... self.index = self.index - 1
... return self.data[self.index]
...
>>> for each in reverse_iterator(['a', 1, 2, 3, 'c', 17]):
... print each
...
17
c
3
2
1
a
Я знаю, что итератор не идет назад, но я уверен, что в общем случае этого сделать невозможно. Вместо этого напишите итератор, который просматривает дискретную коллекцию в обратном порядке.
Редактировать вы также можете использовать функцию reversed()
чтобы получить обратный итератор для любой коллекции, чтобы вам не приходилось писать свой собственный:
>>> it = reversed(['a', 1, 2, 3, 'c', 17])
>>> type(it)
<type 'listreverseiterator'>
>>> for each in it:
... print each
...
17
c
3
2
1
a
Ответ 3
Итератор по определению является объектом с методом next()
- без упоминания prev()
. Таким образом, вы либо должны кэшировать свои результаты, чтобы вы могли вернуться к ним или переопределить свой итератор, чтобы он возвращал результаты в последовательности, в которой вы хотите.
Ответ 4
По вашему вопросу, похоже, что вы хотите что-то вроде этого:
class buffered:
def __init__(self,it):
self.it = iter(it)
self.buf = []
def __iter__(self): return self
def __next__(self):
if self.buf:
return self.buf.pop()
return next(self.it)
def push(self,item): self.buf.append(item)
if __name__=="__main__":
b = buffered([0,1,2,3,4,5,6,7])
print(next(b)) # 0
print(next(b)) # 1
b.push(42)
print(next(b)) # 42
print(next(b)) # 2
Ответ 5
Вы можете обернуть свой итератор в помощник итератора, чтобы он мог вернуться назад. Он будет хранить повторяющиеся значения в коллекции и использовать их при обратном направлении.
class MemoryIterator:
def __init__(self, iterator : Iterator):
self._iterator : Iterator = iterator
self._array = []
self._isComplete = False
self._pointer = 0
def __next__(self):
if self._isComplete or self._pointer < len(self._array):
if self._isComplete and self._pointer >= len(self._array):
raise StopIteration
value = self._array[self._pointer]
self._pointer = self._pointer + 1
return value
try:
value = next(self._iterator)
self._pointer = self._pointer + 1
self._array.append(value)
return value
except StopIteration:
self._isComplete = True
def prev(self):
if self._pointer - 2 < 0:
raise StopIteration
self._pointer = self._pointer - 1
return self._array[self._pointer - 1]
Использование может быть похоже на это:
my_iter = iter(my_iterable_source)
memory_iterator = MemoryIterator(my_iter)
try:
if forward:
print(next(memory_iterator))
else:
print(memory_iterator.prev())
except StopIteration:
pass
Ответ 6
я думаю, что это поможет вам решить вашу проблему
class TestIterator():
def __init__(self):'
self.data = ["MyData", "is", "here","done"]
self.index = -1
#self.index=len(self.data)-1
def __iter__(self):
return self
def next(self):
self.index += 1
if self.index >= len(self.data):
raise StopIteration
return self.data[self.index]
def __reversed__(self):
self.index = -1
if self.index >= len(self.data):
raise StopIteration
return self.data[self.index]
r = TestIterator()
itr=iter(r)
print (next(itr))
print (reversed(itr))
Ответ 7
ls = [' a', 5, ' d', 7, 'bc',9, ' c', 17, '43', 55, 'ab',22, 'ac']
direct = -1
l = ls[::direct]
for el in l:
print el
Где прямой - -1
для обратного или 1
для обычного.
Ответ 8
Python вы можете использовать список и индексирование для имитации итератора:
a = [1,2,3]
current = 1
def get_next(a):
current = a[a.index(current)+1%len(a)]
return current
def get_last(a):
current = a[a.index(current)-1]
return current # a[-1] >>> 3 (negative safe)
если ваш список содержит дубликаты, вам придется отслеживать индекс отдельно:
a =[1,2,3]
index = 0
def get_next(a):
index = index+1 % len(a)
current = a[index]
return current
def get_last(a):
index = index-1 % len(a)
current = a[index-1]
return current # a[-1] >>> 3 (negative safe)
Ответ 9
пожалуйста, посмотрите эту функцию, сделанную Мортеном Пийбелехтом. Это дает (предыдущий, текущий, следующий) кортеж для каждого элемента итерируемого.
https://gist.github.com/mortenpi/9604377