python - 计算字母在单词中出现的次数,并将其以以下格式:

标签 python python-3.x error-handling count letter

我必须创建一个程序,该程序给定一个短语来计算字母在每个单词中出现的次数并以这种方式打印:

输入:

i see it

输出:
[('i', 1), ('s', 1), ('e', 2), ('i', 1), ('t', 1)]

我的代码仅适用于第一个单词。您能帮我吗?
inicialString=str(input())

words=inicialString.split(" ")
def countTheLetters(t):
 for word in words: 
  thingsList=[]
  for x in word:
   n=word.count(x)
   j=x,n
   thingsList.append(j)
  return thingsList

print(countTheLetters(words))

我的输出:
[('i', 1)]

我试图替换返回的ThingsList,但是它仅适用于最后一个单词。

最佳答案

您每次都要通过thingsList循环清空for word in words:,因此您只会得到最后一个单词。

在第一个thingsList = []语句之前放置for

关于python - 计算字母在单词中出现的次数,并将其以以下格式:,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53469949/

相关文章:

python - ec2 等待超时 [Python]

error-handling - 当您使用 OAuth 2.0 构建 restful 服务时,您会使用自定义错误字段还是 OAuth 2.0 的错误字段?

postgresql - 陷阱特定的命名唯一约束异常

Java 我在这里做错了什么?

Python 函数装饰器调用

python - 使用 selenium webdriver 作为基类 python

python - 在 Windows 10 中安装适用于 Python 3.7.1 的 Mayavi

python - python 中与本地和全局库的相对导入

python - 如何模拟Python中的模块但不是所有方法

python - Pygame: Rect() 参数到底是什么?它们代表什么?