Most Pythonic Way to Split an Array by Repeating Elements

前端 未结 11 1283
星月不相逢
星月不相逢 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:19

    Too clever by half, and only offered because the obvious right way to do it seems so brute-force and ugly:

    class joiner(object):
      def __init__(self, N, data = (), gluing = False):
        self.data = data
        self.N = N
        self.gluing = gluing
      def __add__(self, to_glue):
        # Process an item from itertools.groupby, by either
        # appending the data to the last item, starting a new item,
        # or changing the 'gluing' state according to the number of
        # consecutive delimiters that were found.
        N = self.N
        data = self.data
        item = list(to_glue[1])
        # A chunk of delimiters;
        # return a copy of self with the appropriate gluing state.
        if to_glue[0]: return joiner(N, data, len(item) < N)
        # Otherwise, handle the gluing appropriately, and reset gluing state.
        a, b = (data[:-1], data[-1] if data else []) if self.gluing else (data, [])
        return joiner(N, a + (b + item,))
    
    def split_on_multiple(data, delimiter, N):
      # Split the list into alternating groups of delimiters and non-delimiters,
      # then use the joiner to join non-delimiter groups when the intervening
      # delimiter group is short.
      return sum(itertools.groupby(data, delimiter.__eq__), joiner(N)).data
    

提交回复
热议问题