Most Pythonic Way to Split an Array by Repeating Elements

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

    Here's another way of doing this:

    def split_multi_delimiter(items, delimiter, num_wanted):
        def remove_delimiter(objs):
            return [obj for obj in objs if obj != delimiter]
    
        ranges = [(index, index+num_wanted) for index in xrange(len(items))
                  if items[index:index+num_wanted] == [delimiter] * num_wanted]
    
        last_end = 0
        for range_start, range_end in ranges:
            yield remove_delimiter(items[last_end:range_start])
            last_end = range_end
    
        yield remove_delimiter(items[last_end:])
    
    items = ['a', 'b', 'X', 'X', 'c', 'd', 'X', 'X', 'f', 'X', 'g']
    print list(split_multi_delimiter(items, "X", 2))
    

提交回复
热议问题