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

2024-09-28 05:17:44 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

感谢您的帮助。提前谢谢!你知道吗


Tags: textinpycount字母linenotall
1条回答
网友
1楼 · 发布于 2024-09-28 05:17:44

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})

相关问题 更多 >

    热门问题