Most Pythonic Way to Split an Array by Repeating Elements

前端 未结 11 1258
星月不相逢
星月不相逢 2021-02-13 09:51

I have a list of items that I want to split based on a delimiter. I want all delimiters to be removed and the list to be split when a delimiter occurs twice. F

11条回答
  •  迷失自我
    2021-02-13 10:10

    I don't think there's going to be a nice, elegant solution to this (I'd love to be proven wrong of course) so I would suggest something straightforward:

    def nSplit(lst, delim, count=2):
        output = [[]]
        delimCount = 0
        for item in lst:
            if item == delim:
                delimCount += 1
            elif delimCount >= count:
                output.append([item])
                delimCount = 0
            else:
                output[-1].append(item)
                delimCount = 0
        return output
    

     

    >>> nSplit(['a', 'b', 'X', 'X', 'c', 'd', 'X', 'X', 'f', 'X', 'g'], 'X', 2)
    [['a', 'b'], ['c', 'd'], ['f', 'g']]
    

提交回复
热议问题