为什么我的字典值不是以整数形式存储的?

时间:2014-02-01 22:20:51

标签: python python-3.x

我正在编写一个函数,它返回字符串中每个字母的出现次数:

def count_all(text):
    text = text.lower()
    counts = {}
    for char in text:
        if char not in counts:
            counts.setdefault(char,[1])
        else:
            counts[char] = counts[char] + 1
    print(counts)

count_all('banana')

但是当我尝试运行它时,我收到此错误消息:

Traceback (most recent call last):
  File "countall.py", line 11, in <module>
    count_all('banana')
  File "countall.py", line 8, in count_all
    counts[char] = counts[char] + 1
TypeError: can only concatenate list (not "int") to list

我怀疑它正在读取键char的值作为包含单个项而不是整数的列表,但我不完全确定。我在为每个字母创建密钥并将其值分配给1时没有任何问题,因为这是在我注释掉else子句时打印出来的内容:

Mac:python mac$ python3 countall.py
{'a': [1], 'b': [1], 'n': [1]}

感谢任何帮助。提前谢谢!

1 个答案:

答案 0 :(得分:8)

  

我怀疑它正在将key char的值读作一个包含单个项而不是整数的列表

确切地说,因为您将其设置为列表:counts.setdefault(char,[1])。只是不要这样做,它会工作:counts.setdefault(char,1)setdefault实际上是不必要的,因为您已经检查了char not in counts,因此您可以counts[char] = 1

另请注意,Python已经内置了此算法:

>>> from collections import Counter
>>> Counter('banana')
Counter({'a': 3, 'n': 2, 'b': 1})