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

后端 未结 11 1197
渐次进展
渐次进展 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 01:58

    This may not be the best way to go about doing it, but you can look for the first non-None entry and the last non-None entry and then check the slice for None. e.g.:

    def is_continuous(seq):
        try:
            first_none_pos = next(i for i,x in enumerate(seq) if x is not None)
            #need the or None on the next line to handle the case where the last index is `None`.
            last_none_pos = -next(i for i,x in enumerate(reversed(seq)) if x is not None) or None
        except StopIteration: #list entirely of `Nones`
            return False
        return None not in seq[first_none_pos:last_none_pos]
    
    assert is_continuous([1,2,3,None,None]) == True
    assert is_continuous([None, 1,2,3,None]) == True
    assert is_continuous([None, None, 1,2,3]) == True
    assert is_continuous([None, 1, None, 2,3]) == False
    assert is_continuous([None, None, 1, None, 2,3]) == False
    assert is_continuous([None, 1, None, 2, None, 3]) == False
    assert is_continuous([1, 2, None, 3, None, None]) == False
    

    This will work for any sequence type.

提交回复
热议问题