How to make a custom object iterable?

前端 未结 3 948
北海茫月
北海茫月 2020-12-01 16:02

I have a list of custom-class objects (sample is below).

Using: list(itertools.chain.from_iterable(myBigList)) I wanted to \"merge\" all o

3条回答
  •  遥遥无期
    2020-12-01 16:38

    You can subclass list as well:

    class Direction(list):
        def __init__(self, seq=[], id_=None):
            list.__init__(self,seq)
            self.id = id_ if id_ else id(self)
    
        def __iter__(self):
            it=list.__iter__(self) 
            next(it)                       # skip the first...
            return it  
    
    d=Direction(range(10))
    print(d)       # all the data, no iteration
    # [0, 1, 2, 3, 4]
    
    print (', '.join(str(e) for e in d))     # 'for e in d' is an iterator
    # 1, 2, 3, 4
    

    ie, skips the first.

    Works for nested lists as well:

    >>> d1=Direction([range(5), range(10,15), range(20,25)])
    >>> d1
    [range(0, 5), range(10, 15), range(20, 25)]
    print(list(itertools.chain.from_iterable(d1)))
    [10, 11, 12, 13, 14, 20, 21, 22, 23, 24]          
    

提交回复
热议问题