在 Python 中计算字符串中的重复字符 [英] Counting repeated characters in a string in Python

查看:67
本文介绍了在 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 的回答很好 - 我不熟悉集合模块.我将来会使用它.他的回答比我的更简洁,技术上也更胜一筹.我建议使用他的代码而不是我的代码.

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

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