设置循环到coun

2024-04-25 17:07:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我是:

  1. 以字符串形式获取用户输入。你知道吗
  2. 使用嵌套for循环计算每个字母出现的次数。你知道吗

现在,假设一切都是小写的。你知道吗

这就是我想要的结果。你知道吗

please enter a sentence: this is a test

a : 1

e : 1

h : 1

i : 2

s : 3

t : 3

到目前为止,在Python中,我可以做到:

sentence = input("Please enter a sentence: ")

我知道答案需要一个计数器和一个嵌套的for循环。你知道吗

for alpha in

['a','b','c',........,'z']:

Tags: 字符串用户testforinputis字母this
2条回答
sentence = input("Enter the sentence: ")
count = 0

sentence = sentence.lower()

for letters in ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']:
    for letter in sentence:
            if letters == letter:
                count += 1
    if (count != 0):
        print (letters,":",count)
        count = 0

你不能在收集模块中使用内置的Counter函数吗。你知道吗

只需从collections模块导入counter,然后执行以下操作:

cString = Counter(SomeString)
#return the cString object

#returns the object in order of occurrence.
cString.most_common

编辑:

然而,如果像我假设的那样,这是家庭作业,你需要用最基本的方式来做(而且不给你答案),那么这些就是你需要采取的步骤。你知道吗

  1. 构建一个以字符串作为参数的函数
  2. 有一个包含字母表中所有字符的数组
  3. 对于alpha数组中的每个项目,将项目与输入字符串中的每个项目进行比较,以获得出现次数
  4. 向字典中添加字符和计数的键值对
  5. 返回/打印词典

相关问题 更多 >