Count consecutive characters

后端 未结 9 1614
别那么骄傲
别那么骄傲 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:34

    You only need to change len(word) to len(word) - 1. That said, you could also use the fact that False's value is 0 and True's value is 1 with sum:

    sum(word[i] == word[i+1] for i in range(len(word)-1))
    

    This produces the sum of (False, True, True, False) where False is 0 and True is 1 - which is what you're after.

    If you want this to be safe you need to guard empty words (index -1 access):

    sum(word[i] == word[i+1] for i in range(max(0, len(word)-1)))
    

    And this can be improved with zip:

    sum(c1 == c2 for c1, c2 in zip(word[:-1], word[1:]))
    

提交回复
热议问题