您好,我以前问过这个问题,我想调整我现在的代码。我想调整此代码,以便如果文本字符串中不存在字母,它仍会返回指定的值0
count = {}
for l in text.lower():
if l in let:
if l in count.keys():
count[l] += 1
else:
count[l] = 1
return count
它当前返回以下内容:
example = "Sample String"
print(func(example, "sao")
{'s': 2, 'a' : 1}
这将是我想要的输出
example = "Sample String"
print(func(example, "sao"))
{'s': 2, 'a' : 1, 'o' :0}
您可以使用Dict Comprehensions和str.count:
如果您不介意使用专门为您的目的而设计的工具,那么以下方法可以:
否则,可以在函数中显式设置所有缺少的值
相关问题 更多 >
编程相关推荐