计算在Python中,一个字符在一行中重复了多少次

计算在Python中,一个字符在一行中重复了多少次,python,if-statement,count,Python,If Statement,Count,我目前正在尝试解决一个在Python中计算一行中重复字符的问题 这段代码一直工作到字符串中最后一个不同的字符,我不知道如何解决这个问题 def repeating(word): count=1 tmp = "" res = {} for i in range(1, len(word)): tmp += word[i - 1] if word[i - 1] == word[i]: count += 1

我目前正在尝试解决一个在Python中计算一行中重复字符的问题

这段代码一直工作到字符串中最后一个不同的字符,我不知道如何解决这个问题

def repeating(word): 
    count=1
    tmp = ""
    res = {}
    for i in range(1, len(word)):
        tmp += word[i - 1]
        if word[i - 1] == word[i]:
            count += 1
        else :
            res[tmp] = count
            count = 1
            tmp = ""

    return res

word="aabc"
print (repeating(word))
给定的输出应该是{'aa':2,'b':1,'c':1}, 但是我得到了{'aa':2,'b':1}

如何解决此问题?

我建议使用
集合中的
模块。它正是你想要达到的目标

from collections import Counter

wourd = "aabc"
print(Counter(word))
# Counter({'a': 2, 'b': 1, 'c': 1})

但是如果你想自己实现它,我应该知道
str
是一个可移植的。因此,您可以用一个简单的循环遍历每个字母

此外,还有一个叫做的东西,在这个场景中非常方便。通常,您必须检查是否已定义密钥(在本例中为字母)。如果没有,则必须创建该密钥。如果使用的是
defaultdict
,则可以定义每个新键都有某个默认值

from collections import defaultdict

def repeating(word):
    counter = defaultdict(int)
    for letter in word:
       counter[letter] += 1
    return counter
结果将是类似的:

In [6]: repeating('aabc')
Out[6]: defaultdict(int, {'a': 2, 'b': 1, 'c': 1}) 

在这种情况下,您可以使用为您完成所有工作的

>>> from collections import Counter
>>> Counter('aabc')
Counter({'a': 2, 'c': 1, 'b': 1})
您还可以对字符串中的字母进行迭代,因为这是可迭代的。但是我会使用集合中的defaultdict来保存“计数”部分

>>> from collections import defaultdict
>>> 
>>> def repeating(word): 
...     res = defaultdict(int)
...     for letter in word:
...         res[letter] +=1
...     return res
... 
>>> word="aabc"
>>> print (repeating(word))
defaultdict(<type 'int'>, {'a': 2, 'c': 1, 'b': 1})
>>从集合导入defaultdict
>>> 
>>>def重复(word):
...     res=defaultdict(int)
...     对于大写字母:
...         res[字母]+=1
...     返回res
... 
>>>word=“aabc”
>>>打印(重复(单词))
defaultdict(,{'a':2,'c':1,'b':1})

Python(和大多数语言)中的索引从
0
开始。更改为
范围(len(word))
。重复字符的确切含义是什么?字符串中连续出现的相同字符?根据标记的dup,
范围(x,y)
x
开始,而不是
x-1
,索引从0开始。在python2中也可以正常工作。你是对的,我更新了我的答案。