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

后端 未结 11 1205
渐次进展
渐次进展 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:10

    This algorithm does the work with a few drawbacks (it removes items form the list). But it's a solution.

    Basically if you remove all continuous None from start and the end. And if you found some None in the list then the integers are not in a continuous form.

    def is_continuous(seq):
        while seq and seq[0] is None: del seq[0]
        while seq and seq[-1] is None: del seq[-1]
    
        return None not in seq
    
    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
    

    Yet, another example of how small code could become evil.

    I wish a strip() method were available for list.

提交回复
热议问题