[英]TypeError: unsupported operand type(s) for *: 'NoneType' and 'int'
[英]TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'
我正在尝试计算字符串中每个字符的数量
我的代码在这里:
def CharCount(string):
mydict = {}
for char in string:
mydict[char] = mydict.get(char) + 1
return '\n'.join(['%s,%s' % (c, n) for c, n in mydict.items()])
if __name__ == '__main__':
print CharCount("abcda")
在运行以上代码时,我得到以下错误:
TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'
如果key
不在字典中,则dict.get(key)
默认返回None
。 提供有用的默认值:
for char in string:
mydict[char] = mydict.get(char, 0) + 1
但是,存在一个更好的方法: collections.defaultdict
:
from collections import defaultdict
mydict = defaultdict(int)
for char in string:
mydict[char] += 1
from collections import Counter
mydict = Counter(string)
初次使用aceess char
时, dict.get(char)
返回None
,而不是0
。 这应该解决:
mydict[char] = (mydict.get(char) if char in mydict else 0) + 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.