字符串上的字母计数(counting letters in python)

Python newb here。我正在尝试计算给定字符串中字母“a”的数量。代码如下。它不断在字符串“banana”中返回 1 而不是 3。任何输入赞赏

Python newb here。我正在尝试计算给定字符串中字母“a”的数量。代码如下。它不断在字符串“banana”中返回 1 而不是 3。任何输入赞赏

def count_letters(word, char):
    count = 0
    while count <= len(word):
        for char in word:
            if char == word[count]:
                count += 1
            return count
print count_letters('banana','a')
45

其他答案显示你的代码有什么问题。但也有一个内置的方法来做到这一点,如果你不只是这样做一个练习:

>>> 'banana'.count('a')
3

Danben 给出了此更正版本:

def count_letters(word, char):
  count = 0
  for c in word:
    if char == c:
      count += 1
  return count

这里有一些其他的方法来做到这一点,希望他们会教你更多关于 Python!

类似,但较短的for循环。利用布尔可以变成 1,如果为 true 和 0,如果为 false 的事实:

def count_letters(word, char):
  count = 0
  for c in word:
    count += (char == c)
  return count

循环的缩写通常可以转换为列表 / 生成器理解。这将创建一个与每个字母相对应的整数列表,如果字母不匹配,则为0char,如果匹配,则为 1,然后对它们求和:

def count_letters(word, char):
  return sum(char == c for c in word)

下一个过滤掉所有不匹配char的字符,并计算剩下多少:

def count_letters(word, char):
  return len([c for c in word if c == char])
12

一个问题是,您正在使用count来引用您正在检查的单词中的位置以及您看到的char的数量,并且您正在使用char来引用您正在检查的输入字符和字符串中的当前字符。改用单独的变量。

此外,将return语句移到循环之外;否则,在检查第一个字符后,您将始终返回。

最后,您只需要一个循环来遍历字符串,摆脱外部while循环,您将不需要跟踪字符串中的位置。

采取这些建议,你的代码看起来像这样:

def count_letters(word, char):
  count = 0
  for c in word:
    if char == c:
      count += 1
  return count
7

一个简单的方法如下:

def count_letters(word, char):
    return word.count(char)

或者,还有另一种方式直接计算每个元素:

from collections import Counter
Counter('banana')

当然,您可以指定一个元素,例如

Counter('banana')['a']
6

您的return在 for 循环中!小心缩进,您希望行return count在循环之外。因为 for 循环遍历word中的所有字符,所以完全不需要外部 while 循环。

清理版本:

def count_letters(word, to_find):
    count = 0
    for char in word:
        if char == to_find:
            count += 1
    return count

本站系公益性非盈利分享网址,本文来自用户投稿,不代表码文网立场,如若转载,请注明出处

(747)
“WPM”如何在打字速度应用程序中计算
上一篇
导入docx动态模块时未定义模块导出函数(PyInit_etree)
下一篇

相关推荐

发表评论

登录 后才能评论

评论列表(71条)