在Python中计算列表中的特定字符串

时间:2014-01-27 06:30:27

标签: python

我想在列表中计算'fizz'并且我在下面写了代码并且它没有用。告诉我原因并提供解决方案。我正在做this教程,我必须编写代码作为他们的指令,但我无法做他们所说的或者我误解了他们。

count = 0
def fizz_count(x):
    for string in x:
        if string == 'fizz':
            count = count + 1
        else:
            count = count
    return count

如果你想检查你的答案是否正确,那么你必须通过解释它here来检查它。请注意,我不是在调用自己的函数。相反,它们是Codecademy教程中的内置功能,它通过调用函数来检查函数。

3 个答案:

答案 0 :(得分:0)

您需要在for循环中包含count变量,并且不需要else条件

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

您也可以将您的功能编写为

def fizz_count(x):
    return x.count('fizz')

答案 1 :(得分:-1)

请看下面这段代码。我做了一些修正。我修复了一些语法错误和一些缩进错误。看看吧:

def fizz_count(x):
    count = 0
    for string in x:
        if string == 'fizz':
            count = count + 1
        else:
            count = count
    return count


str1 = fizz_count(['fizzers','fizzerlss','fizz','fizz'])
print str1

答案 2 :(得分:-3)

编辑:由于投票减少而获得更多解释

考虑使用全局变量count的方法(全局变量,因为它不在函数内),您需要做两次调整:

  • 您需要使用关键字count
  • 在本地提供global
  • 由于您使用全局变量,因此无需返回它,因为它仍然可用

代码:

count = 0

def fizz_count(x):
    global count # make count available for writing in the local scope

    for string in x:
        if string == 'fizz':
            count = count + 1
    else:
        count = count

现在实际上不建议使用全局变量,特别是对于这种类型的任务,因为它需要更多的时间来加载,你必须处理当前的状态和类似的东西,所以你宁愿引入一个局部变量并像你一样通过return语句传递它。

  • count = 0置于功能

代码

# we put count = 0 into the function

def fizz_count(x):
    count = 0 # right here

    for string in x:
        if string == 'fizz':
            count = count + 1
    else:
        count = count

    return count

现在新的count将在函数中初始化为零。

现在还有两件事:

  • else声明
  • 和增量

由于else语句在循环之外,因此只有在循环期间if条件从不True时才会执行。这有一些用例。但是你通常会把它放在循环中。但是,在你的情况下,它基本上不会改变任何东西,这就是为什么它可以完全删除。

嗯,第二点是增量可以写成count += 1,这被认为更具可读性,因为它不那么笨拙,第二个count被合并到+= < / p>

因此最终函数可以像这样编写

def fizz_count(x):
    count = 0 

    for string in x:
        if string == 'fizz':
            count += 1

    return count

检查其他答案的合理解决方案