python - Python初学者任务
问题描述
我正在努力学习python。我已经到了我们正在学习“for”循环的地步,并且有点咸菜。第一项任务是构建一个计算所有空格的函数,我的解决方案是:
def count_spaces(s):
cnt = 0
for char in s:
if char == " ":
cnt = cnt+1
return cnt
现在我正在尝试构建一个新函数,它可以接受字符串、字符并返回特定字符的计数
例如:
print(count_char("Hello world!", " ")
屏幕将显示 1(找到 1 个空格)这是我卡住的地方:
def count_char(s, c):
s=[...]
num = 0
for x in s:
if x == x:
num = s.count(c)
return num
它只返回 0 ....
请帮忙
解决方案
你在你s
的函数开始时覆盖你的论点:
s = [...]
这使得其余的事情变得不可能。不要那样做!:)
如果您被允许使用该count
方法(就像您的代码正在做的那样),您根本不需要for
循环:
def count_char(s: str, c: str) -> int:
"""The number of character c in string s."""
return s.count(c)
如果您想在不使用 的情况下执行此操作count
,则可以完全像您的count_space
函数一样编写它,但将 替换" "
为c
参数:
def count_char(s: str, c: str) -> int:
"""The number of character c in string s."""
cnt = 0
for char in s:
if char == c:
cnt = cnt+1
return cnt
或者您可以将for
理解与sum
函数一起使用:
def count_char(s: str, c: str) -> int:
"""The number of character c in string s."""
return sum(1 if char == c else 0 for char in s)
或者您可以使用计数器:
from collections import Counter
def count_char(s: str, c: str) -> int:
"""The number of character c in string s."""
return Counter(s)[c]
推荐阅读
- r - 返回从数据框中修剪了多少修剪
- sql - 在我将身份规范更改为“是”后,为什么在 SQL Server 中它又变回了“否”?
- r - pglm 带偏移量的固定效应泊松模型
- mysql - 无法在我的数据库上运行特定的 SQL 查询
- laravel - 在 Vue 组件中解析 JSON 编码的数据
- c - 创建pthread时如何正确调用函数?
- sql - 为 SQL Server 和 Oracle 编写通用 SQL 以显示日期
- android - Google Play 崩溃日志未使用 Android App Bundle 进行符号化
- javascript - 我应该使用 CSS 还是 Javascript 来显示取决于屏幕大小的信息?重要吗?
- jenkins - 为什么这个 groovy 代码在詹金斯管道脚本中的工作方式不同