gpt4 book ai didi

python - 计算字符串中每个字母的频率

转载 作者:IT老高 更新时间:2023-10-28 20:49:19 25 4
gpt4 key购买 nike

这是一个来自 pyschools 的问题。

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

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

这应该看起来像这样:

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

最佳答案

在 2.7+ 中:

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

更早(2.5+,现在很古老):

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

关于python - 计算字符串中每个字母的频率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10806866/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com