Python中的函数列表

1 投票
9 回答
4158 浏览
提问于 2025-04-18 00:30

我正在Codecademy上遇到一个问题,搞不清楚怎么解决。

我需要做的是让它返回一个单词在列表中出现的次数。

这是它让我做的事情:

写一个函数,计算字符串“fizz”在一个列表中出现的次数。

1. 写一个叫做fizz_count的函数,输入一个列表x。

2. 创建一个变量count,用来记录出现的次数。开始时把它设为零。

3. 对于列表x中的每一个项目,如果这个项目等于字符串“fizz”,就把count变量加一。

4. 循环结束后,返回count变量。

比如,fizz_count(["fizz","cat","fizz"])应该返回2。

然后这是我写的代码:

def fizz_count(x):
    count = 0
    for item in x:
        if item == "fizz":
            count = count + 1
            return count

要查看这个课程,编号是A Day at the Supermarket 4/13

9 个回答

2

把你的返回语句放在for循环的最后面。这样写就可以了:

    for item in x:
        if item == "fizz":
            count+= 1
    return count
3

发生的情况是,当程序执行到return语句时,函数就会结束。你应该做的是在for循环结束后再返回计数的结果:

def fizz_count(x):
    count = 0
    for item in x:
        if item == "fizz":
            count = count + 1
    return count

注意:

  • 在Python中,缩进非常重要,因为这是用来分组代码块的方式。
4

你快到了,只是缩进有问题。你的代码应该是:

def fizz_count(x):
    count = 0
    for item in x:
        if item == "fizz":
            count = count + 1
    return count
4

你在循环里面就返回了count,这样不太对。你应该等把整个列表都遍历完了,再返回结果。

8

你已经很接近了!只是缩进有点问题。

你现在的代码:

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

撰写回答