Count consecutive characters

后端 未结 9 1616
别那么骄傲
别那么骄傲 2020-11-28 06:44

How would I count consecutive characters in Python to see the number of times each unique digit repeats before the next unique digit?

At first, I thought I could do

9条回答
  •  时光说笑
    2020-11-28 07:28

    There is no need to count or groupby. Just note the indices where a change occurs and subtract consecutive indicies.

    w = "111000222334455555"
    iw = [0] + [i+1 for i in range(len(w)-1) if w[i] != w[i+1]] + [len(w)]
    dw = [w[i] for i in range(len(w)-1) if w[i] != w[i+1]] + [w[-1]]
    cw = [ iw[j] - iw[j-1] for j in range(1, len(iw) ) ]
    
    print(dw)  # digits
    ['1', '0', '2', '3', '4']
    print(cw)  # counts
    [3, 3, 3, 2, 2, 5]
    
    w = 'XXYXYYYXYXXzzzzzYYY'
    iw = [0] + [i+1 for i in range(len(w)-1) if w[i] != w[i+1]] + [len(w)]
    dw = [w[i] for i in range(len(w)-1) if w[i] != w[i+1]] + [w[-1]]
    cw = [ iw[j] - iw[j-1] for j in range(1, len(iw) ) ]
    print(dw)  # characters
    print(cw)  # digits
    
    ['X', 'Y', 'X', 'Y', 'X', 'Y', 'X', 'z', 'Y']
    [2, 1, 1, 3, 1, 1, 2, 5, 3]
    

提交回复
热议问题