在 Python 中计算字符串中的重复字符
我想计算每个字符在字符串中重复的次数.除了比较 A-Z 中字符串的每个字符之外,还有什么特别的方法可以做到吗?并增加一个计数器?
I want to count the number of times each character is repeated in a string. Is there any particular way to do it apart from comparing each character of the string from A-Z and incrementing a counter?
更新(参考 安东尼的回答):到目前为止,无论您提出什么建议,我都必须写 26 遍.有没有更简单的方法?
Update (in reference to Anthony's answer): Whatever you have suggested till now I have to write 26 times. Is there an easier way?
我的第一个想法是这样做:
My first idea was to do this:
chars = "abcdefghijklmnopqrstuvwxyz"
check_string = "i am checking this string to see how many times each character appears"
for char in chars:
count = check_string.count(char)
if count > 1:
print char, count
然而,这不是一个好主意!这将扫描字符串 26 次,因此您可能会比其他一些答案多做 26 倍的工作.你真的应该这样做:
This is not a good idea, however! This is going to scan the string 26 times, so you're going to potentially do 26 times more work than some of the other answers. You really should do this:
count = {}
for s in check_string:
if s in count:
count[s] += 1
else:
count[s] = 1
for key in count:
if count[key] > 1:
print key, count[key]
这确保您只遍历字符串一次,而不是 26 次.
This ensures that you only go through the string once, instead of 26 times.
另外,Alex 的回答很好 - 我不熟悉集合模块.我将来会使用它.他的回答比我的更简洁,技术上也更胜一筹.我建议使用他的代码而不是我的代码.