计算连续字符 [英] Count consecutive characters

查看:104
本文介绍了计算连续字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何计算Python中的连续字符以查看每个唯一数字在下一个唯一数字之前重复的次数?

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 something like:

word = '1000'

counter=0
print range(len(word))


for i in range(len(word)-1):
    while word[i]==word[i+1]:
        counter +=1
        print counter*"0"
    else:
        counter=1
        print counter*"1"

这样,我可以看到每个唯一数字重复的次数。但这当然会在 i 达到最后一个值时超出范围。

So that in this manner I could see the number of times each unique digit repeats. But this, of course, falls out of range when i reaches the last value.

在上面的示例中,我希望Python告诉我1重复1,而0重复3次。但是,由于我的while语句,上面的代码失败了。

In the example above, I would want Python to tell me that 1 repeats 1, and that 0 repeats 3 times. The code above fails, however, because of my while statement.

我知道您可以使用内置函数来做到这一点,并且希望采用这种方式。

I know you can do this with just built-in functions and would prefer a solution that way.

推荐答案

那种方式的解决方案,只有基本语句:

A solution "that way", with only basic statements:

word="100011010" #word = "1"
count=1
length=""
if len(word)>1:
    for i in range(1,len(word)):
       if word[i-1]==word[i]:
          count+=1
       else :
           length += word[i-1]+" repeats "+str(count)+", "
           count=1
    length += ("and "+word[i]+" repeats "+str(count))
else:
    i=0
    length += ("and "+word[i]+" repeats "+str(count))
print (length)

输出:

'1 repeats 1, 0 repeats 3, 1 repeats 2, 0 repeats 1, 1 repeats 1, and 0 repeats 1'
#'1 repeats 1'

这篇关于计算连续字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆