【问题标题】:Recursive function to count all items in a nested list?递归函数来计算嵌套列表中的所有项目?
【发布时间】:2014-01-27 06:55:49
【问题描述】:

我正在尝试创建一种方法来计算嵌套列表中的所有项目。所以count([[3, 2] , [2]]) == 3。但是,它是一个 Class 属性,所以我不能简单地这样做:

def count(L, target):
    s = 0
    for i in L: 
        if isinstance(i, list): 
            s += count(i, target)
        else: 
            if i == target: 
                s += 1

    return s 

相反,我尝试这样做,但出现最大递归深度错误。我不确定为什么。在查看代码之前,请记住以下几点:(1) 我希望给定的基本列表仅包含列表,因此其格式为:[ [], ]。此外 (2) 子列表将不包含除项目之外的任何内容:[ [item, item], [item] ]

def count(self, stack=None):
    n = 0
    if stack:
        n += len(stack)
    else:
        for i in self._items:
            if isinstance(i, list):
                n += self.count(i)

    return n

【问题讨论】:

    标签: python list recursion nested


    【解决方案1】:
        if stack:
    

    空列表在布尔上下文中被认为是错误的。你想要if stack is not None

    为什么要使用递归呢?你不需要它。

    def count(self):
        return sum(len(item) for item in self._items)
    

    【讨论】:

    • Lmao ...当我学习一个新概念并尝试将其应用于所有事物时,就会发生这种情况。多么简单的解决方案。我很感激你让我重新振作起来:P
    【解决方案2】:

    如果您的列表仅嵌套一层,这很容易。

    class MyClass:
        def __init__(self, items):
            self.items = items
    
        def count(self):
            return sum(len(x) for x in self.items)
    
    a = MyClass([[3,2],[2]])
    b = MyClass([[1,2,3],[4,5,6],[7],[]])
    print(a.count()) # 3
    print(b.count()) # 7
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-22
      • 2016-05-28
      • 2018-07-25
      • 1970-01-01
      • 2014-12-14
      • 2021-04-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多