Most Pythonic Way to Split an Array by Repeating Elements

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

    In [6]: input = ['a', 'b', 'X', 'X', 'cc', 'XX', 'd', 'X', 'ee', 'X', 'X', 'f']
    
    In [7]: [s.strip('_').split('_') for s in '_'.join(input).split('X_X')]
    Out[7]: [['a', 'b'], ['cc', 'XX', 'd', 'X', 'ee'], ['f']]
    

    This assumes you can use a reserved character such as _ which is not found in the input.

提交回复
热议问题