【问题标题】:Recursively counting occurrences in a nested list of numbers递归计算嵌套数字列表中的出现次数
【发布时间】:2016-05-28 15:54:15
【问题描述】:

我终于开始使用 Python 进行递归,并尝试计算目标数字在 list 中出现的次数。但是,我在计算嵌套的 list 数字中的出现次数时遇到了问题。

例如

def count(lst, target):

    if lst == []:
        return 0
    if lst[0] == target:
        return 1 + count(lst[1:], target)
    else:
        return 0 + count(lst[1:], target)

输出

>>> count( [1,2,3,[4,5,5],[[5,2,1],4,5],[3]], 1 )

Output: 1

Expected output: 2

有没有一种简单的方法可以在 Python 中展平嵌套列表?还是一种简单的方法来解释我的代码中有一个嵌套列表这一事实?

【问题讨论】:

标签: python python-3.x recursion nested-lists flatten


【解决方案1】:
def count(lst, target):
    n = 0
    for i in lst:
        if i == target:
            n += 1
        elif type(i) is list:
            n += count(i, target)
    return n

【讨论】:

    【解决方案2】:

    您只需要一个额外的案例来处理 lst[0] 作为子列表,例如:

    def count(lst, target):
    
        if lst == []:
            return 0
        if lst[0] == target:
            return 1 + count(lst[1:], target)
        # If first element is a list, descend into it to count within it,
        #    and continue with counts of remaining elements
        elif type(lst[0]) == list:
            return count(lst[0], target) + count(lst[1:], target)
        else:
            return 0 + count(lst[1:], target)
    

    【讨论】:

      猜你喜欢
      • 2012-08-03
      • 2018-12-30
      • 1970-01-01
      • 2014-03-31
      • 1970-01-01
      • 2017-06-16
      • 2017-04-14
      • 1970-01-01
      • 2022-01-06
      相关资源
      最近更新 更多