python - 函数列表 Python

标签 python python-2.7 python-3.x

我想在 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/

相关文章:

python-3.x - 无法使用sqlite3在centos 5上编译python3.7

python - 如何使用 web2py.DAL 进行 'between' 查询?

python - ansible-container 不是 JSON 可序列化的

python - 使用极轴在 matplotlib 中进行四重显示

python - 如何将模块中的所有 printf 样式转换为 python 中的格式化样式?

python - 将整数转换为 python 中的字节字符表示时的性能

python - 在文本小部件中标记 - tkinter

python: urllib.request.urlopen 不起作用

python - 在 Python 中使用 BeautifulSoup 从 HTML 中删除回车符

python - 如何改进我的队列系统 - Discord.py