Python初学者探索
我正在努力学习python。 我已经到了我们学习循环的程度 吃了点腌菜。 第一项任务是构建一个计算所有空间的函数,我的解决方案是:Python初学者探索,python,function,loops,Python,Function,Loops,我正在努力学习python。 我已经到了我们学习循环的程度 吃了点腌菜。 第一项任务是构建一个计算所有空间的函数,我的解决方案是: def count_spaces(s): cnt = 0 for char in s: if char == " ": cnt = cnt+1 return cnt 现在我正在尝试构建一个新函数,它可以接受字符串char 并将返回特定字符的计数 例如: print(count_char("Hello
def count_spaces(s):
cnt = 0
for char in s:
if char == " ":
cnt = cnt+1
return cnt
现在我正在尝试构建一个新函数,它可以接受字符串char
并将返回特定字符的计数
例如:
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
请帮助我,我相信而不是
if x == x:
你需要
if x == c:
试试这个
def count_spaces(s, c):
cnt = 0
for char in s:
if char == c:
cnt = cnt+1
return cnt
您正在覆盖函数开头的
s
参数:
s = [...]
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)
这使得剩下的事情不可能做到。不要那样做!:)
如果允许您使用count
方法(就像您的代码所做的那样),则根本不需要for
循环:
def count_char(s: str, c: str) -> int:
"""The number of character c in string s."""
return s.count(c)
如果不想使用count
,可以完全按照count\u 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
或者您可以使用进行理解,同时使用求和
功能:
s = [...]
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]
删除s=[…]
。无论…
是什么,它都不应该存在,因为s
是一个输入参数,您不想更改它
关于代码:它只能是:
count = string.count(substring)
因为str.count()
如果您想避免使用内置方法并自己实现它,那么您应该替换
num=s.count(c)
使用num+=1
和x==x
(因为x始终等于x,您将计算所有字符)使用x==c
如下:
def count_char(s, c):
num = 0
for x in s:
if x == c:
num += 1
return num
祝你好运,学习愉快 x==x
总是正确的。这与您的第一个代码完全相同,唯一的区别在于您不是在寻找“
,而是在寻找c
。您也可以选择cnt+=1
而不是cnt=cnt+1
。另外,如果您想了解列表的理解,并在一行中完成,请执行def count_spaces(s,c):返回len([x代表s中的x,如果x==c])
。我并不总是建议这样做,因为它会消耗内存,但既然您正在学习循环,为什么不呢!