我正在编写一个函数,返回字符串中每个字母的出现次数:
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]}
感谢您的帮助。提前谢谢!你知道吗
完全正确,因为您将其设置为一个列表:
counts.setdefault(char,[1])
。只要不这样做,它就会工作:counts.setdefault(char,1)
。setdefault
实际上是不必要的,因为您已经检查了char not in counts
,所以您可以只执行counts[char] = 1
。你知道吗另请注意,Python已经内置了此算法:
相关问题 更多 >
编程相关推荐