我想在 Codecademy 上解决这个问题,但我无法解决。 好的,所以我需要做这个,以便它返回列表中某个单词被说的次数。
这是它说要做的:
Write a function that counts how many times the string "fizz" appears in a list.
1.Write a function called fizz_count that takes a list x as input.
2.Create a variable count to hold the ongoing count. Initialize it to zero.
3.for each item in x:, if that item is equal to the string "fizz" then increment the count variable.
4.After the loop, please return the count variable.
For example, fizz_count(["fizz","cat","fizz"]) should return 2.
下面是我写的:
def fizz_count(x):
count = 0
for item in x:
if item == "fizz":
count = count + 1
return count
要看这节课,数字是超市的一天 4/13
最佳答案
你太接近了!你只是弄错了缩进。
你有什么:
for item in x:
if item == 'fizz':
count = count + 1
return count # Returns any time we hit "fizz"!
你需要什么:
for item in x:
if item == 'fizz':
count += 1 # how we normally write this
return count # after the loop, at the base indent level of the function
关于python - 函数列表 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22738796/