递归遍历列表并与值进行比较(python)

时间:2020-06-03 21:31:55

标签: python recursion

任务是浏览列表,将其与值进行比较,然后返回该值出现的次数。比较有效,当我找到匹配的值时,我想将其保存在列表中。然后,我想获取该列表的长度。问题是,每次我再次调用该函数时,列表都会重置,如何避免这种情况?

    def count_occurences(values, value):
        matched_values = []
        if values:
            if values[0] == value:
                matched_values.append(values[0])
                count_occurences(values[1:], value)
            else:
                count_occurences(values[1:], value)
        else:
            return 0
        return len(matched_values)
    count_occurences([1, "one", 2, "two", "two", 3, "three", "three", "three"], "two")

在这种情况下,预期输出为:2。

3 个答案:

答案 0 :(得分:1)

正如@ juanpa.arrivillaga在评论中所述,您正在初始化matched_values以将每个呼叫清空列表,因此您没有有效地返回任何内容。

可以简化脚本,例如:

def count_occurences(values, value):
    if values:
        return (values[0] == value) + count_occurences(values[1:], value)
    return 0

n = count_occurences([1, "one", 2, "two", "two", 3, "three", "three", "three"], "two")
print(n)

打印:

2

答案 1 :(得分:1)

您只需将matched_values分配移到函数外部即可解决当前的问题,如下所示。

matched_values = []

def count_occurences(values, value):
    if values:
        if values[0] == value:
            matched_values.append(values[0])
            count_occurences(values[1:], value)
        else:
            count_occurences(values[1:], value)
    else:
        return 0
    return len(matched_values)
count_occurences([1, "one", 2, "two", "two", 3, "three", "three", "three"], "two")

但是,此代码实际上引发的问题多于其答案。大概您将其作为学习练习来进行,因为您可以轻松地进行此操作而无需特殊功能或递归。因此请记住,我会问你:

  • matched_values的意义是什么?根据定义,它将重复地是同一条目,因此仅知道匹配数就不会添加任何信息
  • 递归是函数式编程中的一种常见模式,但是函数的主要目的是在函数外对变量进行突变-这称为副作用,通常在函数式中被认为是不希望的

考虑到这些,您可能会考虑使用类似的方法,这些方法可以消除列表,并且不涉及突变,也没有副作用。

def count_occurences(values, value):
    if values:
        if values[0] == value:
            return 1 + count_occurences(values[1:], value)
        else:
            return count_occurences(values[1:], value)
    else:
        return 0

(与上面的Andrej Kesely建议的简化基本相同)

答案 2 :(得分:0)

 matched_values = [] 

 def count_occurences(values, value, matched_values):
            if values:
                if values[0] == value:
                    matched_values.append(values[0])
                    count_occurences(values[1:], value, matched_values)
                else:
                    count_occurences(values[1:], value, matched_values)
            else:
                return 0
            return len(matched_values, matched_values)

 count_occurences([1, "one", 2, "two", "two", 3, "three", "three", "three"], "two", matched_values)

在每次调用递归函数count_occurences时,都将重置列表,因为您在函数的开头用以下行matched_values = []重新创建了列表。这将创建一个新变量matched_values,该变量指向内存中的新位置,并且无法访问上一轮发现的内容。

在调用函数之前初始化此空列表可确保每次函数运行时都将访问内存中的相同位置。每个递归调用将在同一列表上操作,并且您不会丢失任何信息。

相关问题