Most Pythonic Way to Split an Array by Repeating Elements

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

    a = ['a', 'b', 'X', 'X', 'c', 'd', 'X', 'X', 'f', 'X', 'g']
    b = [[b for b in q if b != 'X'] for q in "".join(a).split("".join(['X' for i in range(2)]))]
    

    this gives

    [['a', 'b'], ['c', 'd'], ['f', 'g']]

    where the 2 is the number of elements you want. there is most likely a better way to do this.

提交回复
热议问题