我正在编写一个返回字符串中每个字母出现次数的函数:
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/