计算字符串python中的字母

时间:2014-05-28 11:37:12

标签: python list dictionary count counter

我必须编写一个函数countLetters(word),它接受​​一个单词作为参数并返回一个列表,该列表计算每个字母出现的次数。这些字母必须按字母顺序排序。

这是我的尝试:

def countLetters(word):
    x = 0
    y = []
    for i in word:
        for j in range(len(y)):
            if i not in y[j]:
                x = (i, word.count(i))
                y.append(x)
    return y

我第一次尝试没有if i not in y[j]

countLetters("google")

结果是

[('g', 2), ('o', 2), ('o', 2), ('g', 2), ('l', 1), ('e', 1)] 

我想要的时候

[('e', 1), ('g', 2), ('l', 1), ('o', 2)]

当我添加if i not in y[j]过滤器时,它只返回一个空列表[]。

有人可以在这里指出我的错误吗?

6 个答案:

答案 0 :(得分:6)

如果您使用的是Python 2.7 +,我推荐collections模块的Counter

>>> import collections
>>> s = 'a word and another word'
>>> c = collections.Counter(s)
>>> c
Counter({' ': 4, 'a': 3, 'd': 3, 'o': 3, 'r': 3, 'n': 2, 'w': 2, 'e': 1, 'h': 1, 't': 1})

你可以在任何版本的Python中使用额外的一行或两行来做同样的事情:

>>> c = {}
>>> for i in s: 
...     c[i] = c.get(i, 0) + 1

这对检查你的工作也很有用。

按字母顺序排序(以上按频率排序)

>>> for letter, count in sorted(c.items()):
...     print '{letter}: {count}'.format(letter=letter, count=count)
... 
 : 4
a: 3
d: 3
e: 1
h: 1
n: 2
o: 3
r: 3
t: 1
w: 2

或保留一种可以作为词典重用的格式:

>>> import pprint
>>> pprint.pprint(dict(c))
{' ': 4,
 'a': 3,
 'd': 3,
 'e': 1,
 'h': 1,
 'n': 2,
 'o': 3,
 'r': 3,
 't': 1,
 'w': 2}

最后,将其作为列表:

>>> pprint.pprint(sorted(c.items()))
[(' ', 4),
 ('a', 3),
 ('d', 3),
 ('e', 1),
 ('h', 1),
 ('n', 2),
 ('o', 3),
 ('r', 3),
 ('t', 1),
 ('w', 2)]

答案 1 :(得分:2)

我认为问题在于你的外部for循环,因为你正在迭代单词中的每个字母。

如果单词包含多个某个字母,例如"bees",则当它迭代此字时,它现在将'e'的数量计为for的两倍tally= {} for s in check_string: if tally.has_key(s): tally[s] += 1 else: tally[s] = 1 循环不区分唯一值。看看字符串迭代器,这可能会更多地澄清这一点。我不确定这会解决你的问题,但这是我注意到的第一件事。

您可以尝试这样的事情:

{{1}}

然后您就可以从该词典中检索每个字母的计数。

答案 2 :(得分:1)

您的列表y始终为空。你永远不会进入循环for j in range(len(y))

P.S。你的代码不是非常pythonic

答案 3 :(得分:1)

我不确定你的预期输出是什么,根据问题陈述,似乎你应该先排序这个单词以获得排序顺序的字母数。下面的代码可能会有所帮助:

def countLetters(word):
    letter = []
    cnt = []
    for c in sorted(word):
        if c not in letter:
            letter.append(c)
            cnt.append(1)
        else:
            cnt[-1] += 1
    return zip(letter, cnt)

print countLetters('hello')

这会给你[(' e',1),(' h',1),(' l',2),(&# 39; o',1)]

答案 4 :(得分:1)

适用于最新的Py3和Py2

def countItems(iter):
  from collections import Counter
  return sorted(Counter(iter).items())

答案 5 :(得分:1)

使用来自@ Aaron Hall

的回答的字典和pprint
import pprint
def countLetters(word):
    y = {}
    for i in word:
    if i in y:
        y[i] += 1
    else:
        y[i] = 1
    return y

res1 = countLetters("google")
pprint.pprint(res1)

res2 = countLetters("Google")
pprint.pprint(res2)

输出:

  

{' e':1'':2,' l':1,' o':2}

     

{' G':1,' e':1' g':1,' l':1,&# 39; o':2}

相关问题