Most Pythonic Way to Split an Array by Repeating Elements

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

    Here's a way to do it with itertools.groupby():

    import itertools
    
    class MultiDelimiterKeyCallable(object):
        def __init__(self, delimiter, num_wanted=1):
            self.delimiter = delimiter
            self.num_wanted = num_wanted
    
            self.num_found = 0
    
        def __call__(self, value):
            if value == self.delimiter:
                self.num_found += 1
                if self.num_found >= self.num_wanted:
                    self.num_found = 0
                    return True
            else:
                self.num_found = 0
    
    def split_multi_delimiter(items, delimiter, num_wanted):
        keyfunc = MultiDelimiterKeyCallable(delimiter, num_wanted)
    
        return (list(item
                     for item in group
                     if item != delimiter)
                for key, group in itertools.groupby(items, keyfunc)
                if not key)
    
    items = ['a', 'b', 'X', 'X', 'c', 'd', 'X', 'X', 'f', 'X', 'g']
    
    print list(split_multi_delimiter(items, "X", 2))
    

    I must say that cobbal's solution is much simpler for the same results.

提交回复
热议问题