How to find Run length encoding in python

前端 未结 3 1938
梦毁少年i
梦毁少年i 2021-01-18 06:42

I have an array ar = [2,2,2,1,1,2,2,3,3,3,3]. For this array, I want to find the lengths of consecutive same numbers like:

 values: 2, 1, 2, 3
l         


        
3条回答
  •  感动是毒
    2021-01-18 06:47

    Here is an answer using the high-performance pyrle library for run length arithmetic:

    # pip install pyrle
    # (pyrle >= 0.0.25)
    
    from pyrle import Rle
    
    v = [2,2,2,1,1,2,2,3,3,3,3]
    
    r = Rle(v)
    print(r)
    # +--------+-----+-----+-----+-----+
    # | Runs   | 3   | 2   | 2   | 4   |
    # |--------+-----+-----+-----+-----|
    # | Values | 2   | 1   | 2   | 3   |
    # +--------+-----+-----+-----+-----+
    # Rle of length 11 containing 4 elements
    
    print(r[4])
    # 1.0
    
    print(r[4:7])
    # +--------+-----+-----+
    # | Runs   | 1   | 2   |
    # |--------+-----+-----|
    # | Values | 1.0 | 2.0 |
    # +--------+-----+-----+
    # Rle of length 3 containing 2 elements
    
    r + r + 0.5
    # +--------+-----+-----+-----+-----+
    # | Runs   | 3   | 2   | 2   | 4   |
    # |--------+-----+-----+-----+-----|
    # | Values | 4.5 | 2.5 | 4.5 | 6.5 |
    # +--------+-----+-----+-----+-----+
    # Rle of length 11 containing 4 elements
    

提交回复
热议问题