Most Pythonic Way to Split an Array by Repeating Elements

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

    Very ugly, but I wanted to see if I could pull this off as a one-liner and I thought I would share. I beg you not to actually use this solution for anything of any importance though. The ('X', 3) at the end is the delimiter and the number of times it should be repeated.

    (lambda delim, count: map(lambda x:filter(lambda y:y != delim, x), reduce(lambda x, y: (x[-1].append(y) if y != delim or x[-1][-count+1:] != [y]*(count-1) else x.append([])) or x, ['a', 'b', 'X', 'X', 'c', 'd', 'X', 'X', 'f', 'X', 'g'], [[]])))('X', 2)
    

    EDIT

    Here's a breakdown. I also eliminated some redundant code that was far more obvious when written out like this. (changed above also)

    # Wrap everything in a lambda form to avoid repeating values
    (lambda delim, count:
        # Filter all sublists after construction
        map(lambda x: filter(lambda y: y != delim, x), reduce(
            lambda x, y: (
                # Add the value to the current sub-list
                x[-1].append(y) if
                    # but only if we have accumulated the
                    # specified number of delimiters
                    y != delim or x[-1][-count+1:] != [y]*(count-1) else
    
                    # Start a new sublist
                    x.append([]) or x,
            ['a', 'b', 'X', 'X', 'c', 'd', 'X', 'X', 'f', 'X', 'g'], [[]])
        )
    )('X', 2)
    

提交回复
热议问题