【发布时间】:2021-04-17 14:30:57
【问题描述】:
我需要返回一个字典,计算预定列表中每个字母出现的次数。问题是我需要将大写和小写字母都计算为相同,所以我不能使用 .lower 或 .upper。
因此,例如,如果“t”是要搜索的字母,“这是一个 Python 字符串”应该返回 {'t':3}。
这是我目前所拥有的......
def countLetters(fullText, letters):
countDict = {i:0 for i in letters}
lowerString = fullText.lower()
for i in lowerString:
if i in letters:
countDict[i] += 1
return countDict
'letters' 是条件,fullText 是我要搜索的字符串。
这里明显的问题是,如果测试是“T”而不是“t”,我的代码将不会返回任何内容抱歉我的术语中有任何错误,我对此很陌生。任何帮助将不胜感激!
【问题讨论】:
-
你说不能用
.lower,为什么还要用呢? -
collections 标准库为此提供了 Counter 类
-
循环应该是
for i in lowerString: -
我不确定我是否理解这段代码的问题所在。能否请您出示minimal reproducible example?
-
我使用 .lower 是因为他第一次没有说明我们不应该使用它。他再次向我们提出问题,这次检查大写的附加条件以确保我们不使用 .lower 或 .upper
标签: python string dictionary count