你好,我之前问过这个问题,我想调整我现在的代码。我想调整此代码,以便如果文本字符串中不存在字母,它仍会返回值 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}
最佳答案
如果您不介意使用专为您的目的而设计的工具,则可以使用以下工具:
from collections import Counter
def myfunc(inp, vals):
c = Counter(inp)
return {e: c[e] for e in vals}
s = 'Sample String'
print(myfunc(s, 'sao')
否则,您可以在函数中明确设置所有缺失值。
def func(inp, vals):
count = {e:0 for e in vals}
for s in inp:
if s in count:
count[s] += 1
return count
关于python - 如何创建接受文本字符串并返回包含某些已定义字符出现次数的字典的函数,即使不存在?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67197085/