python - 为什么我的字典值不存储为整数?

标签 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]}

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

最佳答案

I suspect it's reading the value of key char as a list with a single item rather than an integer

没错,因为您将它设置为一个列表: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})

关于python - 为什么我的字典值不存储为整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21504408/

相关文章:

python加入两个csv文件

python - 如何在 keras 中保存整个数据的预测值

python - 如何仅访问 PuLP 问题中的特定变量?

python - 如果列表中有 2 个或更多模式,则模式的随机输出

python - 如何在 Python 3.x 中识别和存储格式化文本文件中的变量和数据?

python - Google App Engine Python - 按 ListProperty 中的密度排序

python - aiohttp:如何在下载响应正文之前有效地检查 HTTP header ?

python - 在 ForeignKey 上设置 unique=True 与使用 OneToOneField 具有相同的效果

python-3.x - 在 matplotlib 中绘制垂直双头箭头

python - 如何在单个子图中绘制数字列表?