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

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

    The natural way to consume sequence elements is to use dropwhile:

    from itertools import dropwhile
    def continuous(seq):
        return all(x is None for x in dropwhile(lambda x: x is not None,
                                                dropwhile(lambda x: x is None, seq)))
    

    We can express this without nested function calls:

    from itertools import dropwhile
    def continuous(seq):
        core = dropwhile(lambda x: x is None, seq)
        remainder = dropwhile(lambda x: x is not None, core)
        return all(x is None for x in remainder)
    

提交回复
热议问题