Найти - Пользователи
Полная версия: Можно ли скопировать итератор?
Начало » Python для новичков » Можно ли скопировать итератор?
1 2
knkd
Первый набросок.
Непонятно, как сделать self._history экземпляром IterPack не впадая в рекурсию?
Хочется возможности менять и его тоже.

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from pprint import pprint

class IterPack(object):
def __init__(self, iterable=None):
self._parent = None
self._iterable = None
self._history = [iterable]

def end(self, deep=1):
deep = abs(int(deep))
if deep <= (len(self._history) - 2):
res = self._history[deep]
else:
res = self._history[1]
return res

def __iter__(self):
if not self._iterable:
self._create_iterator()
return self._iterable.__iter__()

def __call__(self, param):
return self._history[-1](param)

def _create_iterator(self):
res = self._history[0]
for _lambda in self._history[1:]:
res = _lambda(res)
self._iterable = res
return self

def imap(self, _lambda):
res = lambda iterable: (_lambda(item) for item in iterable)
res = IterPack(res)
self._history.append(res)
return self

def ifilter(self, _lambda):
res = lambda iterable: (item for item in iterable if _lambda(item))
res = IterPack(res)
self._history.append(res)
return self

def irange(self, count):
self._history[-1] = xrange(count)
return self


def main():
a = IterPack(xrange(10))
a.imap(lambda x: x**2).imap(lambda x: x + 11).ifilter(lambda x: x%2!=0)
a.end(1).imap(lambda x: x*3)

for x in a: print x
for x in a._history: print x._history if hasattr(x, '_history') else x

print
b = IterPack()
b.irange(5)

for x in b: print x

if __name__ == '__main__':
main()
knkd
Вопрос снимается.
#!/usr/bin/env python
# -*- coding: utf-8 -*-

from pprint import pprint

class IterPack(object):
def __init__(self, iterable=None, parent=None):
self._parent = parent
self._iterable = None
if not self._parent:
self._history = [IterPack(iterable, parent=self)]
else:
self._history = [iterable]
#self._history = [iterable]

def end(self, deep=1):
deep = abs(int(deep))
if deep <= (len(self._history) - 2):
deep = -1 - deep
res = self._history[deep]
else:
res = self._history[1]
return res

def back(self):
res = self._parent if self._parent else self
return res

def __iter__(self):
if not self._iterable:
self._create_iterator()
return self._iterable.__iter__()

def __call__(self, param):
return self._history[-1](param)

def _create_iterator(self):
res = self._history[0]
for _lambda in self._history[1:]:
res = _lambda(res)
self._iterable = res
return self

def imap(self, _lambda):
res = lambda iterable: (_lambda(item) for item in iterable)
res = IterPack(res, parent=self)
self._history.append(res)
return self

def ifilter(self, _lambda):
res = lambda iterable: (item for item in iterable if _lambda(item))
res = IterPack(res, parent=self)
self._history.append(res)
return self

def irange(self, count):
self._history[-1] = IterPack(xrange(count))
return self

def _add(self, iterable):
self._history[-1] = IterPack(iterable, parent=self)
return self

def __str__(self, level=0):
res = []
if level==0: res.append('IterPack START\n')
for item in self._history:
row = "{PS}{INDENT}+ -> {TYPE} {HASH}\n".format(
INDENT = '| '*level,
TYPE = type(item),
HASH = hex(hash(item)),
PS = '|\n' if not level else ''
)
res.append(row)
if hasattr(item, '_history'):
res.extend(item.__str__(level=level+1))
if level==0: res.append('END')
return ''.join(res)


def main():
a = IterPack(xrange(10000))
a.imap(lambda x: x**2).imap(lambda x: x + 11).ifilter(lambda x: x%2!=0)
a.ifilter(lambda x: x%3!=0).ifilter(lambda x: x%7!=0)
a.end().imap(lambda x: x*3).imap(lambda x: x+1).imap(lambda x: x+1).back()

b = IterPack()
b.irange(5).imap(lambda x: x**3).imap(lambda x: x + 11).ifilter(lambda x: x%2!=0)

print list(a)
#print list(b)
print a
#print b

if __name__ == '__main__':
main()
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Powered by DjangoBB