Python itertools模块 可能的Python代码实现

头部

from numbers import Number as _number
from operator import add as _add
_no_arg=object()

accumulate()

def accumulate(iterable, func=None, *, initial=None):
    if func is None:
        func=_add

    iterator=iter(iterable)

    if initial is None:
        try:
            initial=next(iterator)

        except StopIteration:
            return

    yield initial

    for i in iterator:
        initial=func(initial,i)
        yield initial

chain()

def chain(*iterables):
    for iterable in iterables:
        yield from iterable

chain.from_iterable=lambda iterable,/:chain(*iterable)

combinations()

还没写出来……

combinations_with_replacement()

还没写出来……

compress()

def compress(data, selectors):
    for i,j in zip(data,selectors):
        if j:
            yield i

count()

class count:
    def __init__(self,start,step=1):
        if isinstance(start,_number) and isinstance(step,_number):
            self.__start=start
            self.__step=step

        else:
            raise TypeError("a number is required")
    
    def __iter__(self):
        return self

    def __next__(self):
        temp=self.__start
        self.__start+=self.__step
        return temp

cycle()

def cycle(iterable, /):
    save=[]

    for i in iterable:
        yield i
        save.append(i)

    if save:
        while True:
            yield from save

dropwhile()

def dropwhile(predicate, iterable, /):
    it=iter(iterable)

    for i in it:
        if not predicate(i):
            yield i
            yield from it

filterfalse()

def filterfalse(function, iterable, /):
    if function is None:
        for i in iterable:
            if not i:
                yield i
    
    else:
        for i in iterable:
            if not function(i):
                yield i

groupby()

还没写出来

islice()

class islice:
    def __init__(self,iterable,start=None,stop=None,step=None,/):
        if step is None:
            self.__c=0
            step=1
        elif isinstance(step,int) and step>0:
            self.__c=step-1
        else:
            raise ValueError("Step argument for islice() must be None or a positive integer")

        if stop is None:
            stop,start=start,stop

        if start is None:
            start=0
        elif not isinstance(start,int) or start<0:
            raise ValueError("Start argument for islice() must be None or a non-negative integer")

        if stop is None:
            self.__b=None
        elif isinstance(stop,int)and stop>=0:
            self.__b=((stop-start-1)//step+1) if start<stop else 0
        else:
            raise ValueError("Stop argument for islice() must be None or a non-negative integer")

        self.__a=start
        self.__it=iter(iterable)

    def __iter__(self):
        return self

    def __next__(self):
        if self.__b is None:
            pass

        elif self.__b:
            self.__b-=1

        else:
            raise StopIteration

        while self.__a:
            self.__it.__next__()
            self.__a-=1

        self.__a=self.__c
        return self.__it.__next__()

permutations()

还没写出来

product()

还没写出来

repeat()

class _repeat:
    def __init__(self,object,/):
        self.__obj=object

    def __iter__(self):
        return self

    def __next__(self):
        return self.__obj

    def __length_hint__(self):
        raise TypeError("len() of unsized object")

    def __reduce__(self):
        return self.__class__,(self.__obj,)

    def __repr__(self):
        return f'repeat({self.__obj!r})'


class repeat:
    def __new__(cls,object,times=_no_arg):
        if times is _no_arg:
            return _repeat(object)
        return object.__new__(cls)


    def __init__(self,object,times):
        if isinstance(times,int):
            self.__times=times
        else:
            raise TypeError(f"'{object.__class__.__name__}' object cannot be interpreted as an integer")

        self.__obj=object

    def __iter__(self):
        return self

    def __next__(self):
        if self.__times:
            self.__times-=1
            return self.__obj

        raise StopIteration

    def __length_hint__(self):
        return self.__times

    def __reduce__(self):
        return self.__class__,(self.__obj,self.__times)

    def __repr__(self):
        return f'repeat({self.__obj!r}, {self.__times})'

starmap()

def starmap(function, iterable, /):
    for i in iterable:
        yield function(*i)

takewhile()

def takewhile(predicate, iterable, /):
    for i in iterable:
        if predicate(i):
            break
        else:
            yield i

tee()

class node:
    def __init__(self,value):
        self.value = value
        self.next = None


class _tee:
    def __init__(self,iter,node):
        self.iter = iter
        self.node = node

    def __iter__(self):
        return self

    def __next__(self):
        if self.node.next is None:
            try:
                self.node.next = self.node = node(self.iter.__next__())

            except StopIteration as err:
                self.node.next = NotImplemented
                raise err

        elif self.node.next is NotImplemented:
            raise StopIteration

        else:
            self.node = self.node.next

        return self.node.value


def tee(iterable,n=2,/):
    temp = []
    iterator = iter(iterable)
    init = node(None)

    while n:
        temp.append(_tee(iterator,init))
        n-=1

    return tuple(temp)

zip_longest()

class zip_longest:
    def __init__(self,*iterables,fillvalue=None):
        self.__iterators=tuple(iter(i) for i in iterables)
        self.__filevalue=fillvalue

    def __iter__(self):
        return self

    def __next__(self):
        temp=[]
        flag=True

        for i in self.__iterators:
            try:
                temp.append(next(i))
                flag=False
            
            except StopIteration:
                temp.append(self.__filevalue)

        if flag:
            raise StopIteration

        return tuple(temp)

由于本人才疏学浅,代码难免有错误,还请各位多多包涵!
如果发现错误,可以在评论区指正哦~

posted @ 2020-04-10 17:40  NoneType  阅读(342)  评论(1编辑  收藏  举报