Most Pythonic Way to Split an Array by Repeating Elements

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

    Regex, I choose you!

    import re
    
    def split_multiple(delimiter, input):
        pattern = ''.join(map(lambda x: ',' if x == delimiter else ' ', input))
        filtered = filter(lambda x: x != delimiter, input)
        result = []
        for k in map(len, re.split(';', ''.join(re.split(',',
            ';'.join(re.split(',{2,}', pattern)))))):
            result.append([])
            for n in range(k):
                result[-1].append(filtered.__next__())
        return result
    
    print(split_multiple('X',
        ['a', 'b', 'X', 'X', 'c', 'd', 'X', 'X', 'f', 'X', 'g']))
    

    Oh, you said Python, not Perl.

提交回复
热议问题