计算字符串中每个字母的频率 [英] Counting each letter's frequency in a string

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

问题描述

这是来自 pyschools 的问题.

我确实做对了,但我猜会有更简单的方法.这是最简单的方法吗?

def countLetters(word):信函={}单词中的字母:字母字典[字母] = 0单词中的字母:字母字典[字母] += 1返回信函

这应该是这样的:

<预><代码>>>>countLetters('谷歌'){'e':1,'g':2,'l':1,'o':2}

解决方案

在 2.7+ 中:

导入集合字母 = collections.Counter('google')

更早的版本(2.5+,现在已经很古老了):

导入集合字母 = collections.defaultdict(int)单词中的字母:字母[字母] += 1

This is a question from pyschools.

I did get it right, but I'm guessing that there would be a simpler method. Is this the simplest way to do this?

def countLetters(word):
    letterdict={}
    for letter in word:
        letterdict[letter] = 0
    for letter in word:
        letterdict[letter] += 1
    return letterdict

This should look something like this:

>>> countLetters('google')
{'e': 1, 'g': 2, 'l': 1, 'o': 2}

解决方案

In 2.7+:

import collections
letters = collections.Counter('google')

Earlier (2.5+, that's ancient by now):

import collections
letters = collections.defaultdict(int)
for letter in word:
    letters[letter] += 1

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

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