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

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

    Here's a solution inspired by numpy. Get the array indices of all the non-null elements. Then, compare each index to the one following it. If the difference is greater than one, there are nulls in between the non-nulls. If there are no indices where the following index is more than one greater, then there are no gaps.

    def is_continuous(seq):
        non_null_indices = [i for i, obj in enumerate(seq) if obj is not None]
        for i, index in enumerate(non_null_indices[:-1]):
            if non_null_indices[i+1] - index > 1:
                return False
        return True
    

提交回复
热议问题