Pythonic way to determine whether not null list entries are 'continuous'

后端 未结 11 1400
渐次进展
渐次进展 2021-02-01 01:35

I\'m looking for a way to easily determine if all not None items in a list occur in a single continuous slice. I\'ll use integers as examples of not None items

11条回答
  •  眼角桃花
    2021-02-01 02:13

    def contiguous(seq):
        seq = iter(seq)
        all(x is None for x in seq)        # Burn through any Nones at the beginning
        any(x is None for x in seq)        # and the first group
        return all(x is None for x in seq) # everthing else (if any) should be None.
    

    Here are a couple of examples. You can use next(seq) to get the next item from an iterator. I'll put a mark pointing to the next item after each

    example1:

    seq = iter([None, 1, 2, 3, None])        #  [None, 1, 2, 3, None]
                                             # next^
    all(x is None for x in seq)            
                                             #        next^
    any(x is None for x in seq)            
                                             #                    next^ (off the end)
    return all(x is None for x in seq)       # all returns True for the empty sequence
    

    example2:

    seq = iter([1, 2, None, 3, None, None])  #    [1, 2, None, 3, None, None]
                                             # next^
    all(x is None for x in seq)            
                                             #    next^
    any(x is None for x in seq)            
                                             #             next^  
    return all(x is None for x in seq)       # all returns False when 3 is encountered
    

提交回复
热议问题