【问题标题】:Count how many empty list are in a list计算一个列表中有多少个空列表
【发布时间】:2016-02-24 18:59:07
【问题描述】:

我试图找出一个列表中有多少个空列表。 我尝试计算长度为 1 的列表有多少,但在 python 中,[] 的长度为 0,但 [3,[]] 的长度为 2。有没有办法可以计算有多少空列表在一个列表。

示例列表

[[1,[2,3,4],['hello',[]],['weather',['hot','rainy','sunny','cold']]]]

所以我想将 hello 列表计为 1,或者计算这个总字符串中有多少个空列表,即 1。

【问题讨论】:

  • 正如我的示例列表所示。 [ [内容,[更多内容] , [内容,[更多内容] , [内容,[更多内容] ]
  • 您的示例列表有点不清楚:它缺少 2 ]
  • 认为您的示例列表应该[ [1, [2,3,4]], ['hello', []], ['weather', ['hot','rainy','sunny','cold']] ]。对吗?
  • @JRazor 根据上面 OP 的评论,PM 2Ring 很可能是正确的。这意味着您的编辑与 OP 的意图相冲突。

标签: python list loops


【解决方案1】:
def count_empties(lst, is_outer_list=True):
    if lst == []:
        # the outer list does not counted if it's empty
        return 0 if is_outer_list else 1
    elif isinstance(lst, list):
        return sum(count_empties(item, False) for item in lst)
    else:
        return 0

【讨论】:

    【解决方案2】:

    脚本:

    target_list = [[1, [2, 3, 4, [], [1, 2, []]], ['hello', []], ['weather', ['hot', 'rainy', 'sunny', 'cold']]],
                   [[[[1, [], []]]]]]
    target_list2 = []
    target_list3 = [[[[]]]]
    
    
    def count_empty_list(l):
        count = 0
    
        if l == []:
            return 1
        elif isinstance(l, list):
            for sub in l:
                count += count_empty_list(sub)
        else:
            return 0
    
        return count
    
    if __name__ == '__main__':
        print count_empty_list(target_list)
        print count_empty_list(target_list2)
        print count_empty_list(target_list3)
    

    输出:

    /usr/bin/python /Users/ares/PyCharmProjects/comparefiles/TEMP.py
    5
    1
    1
    

    可能没有第一个答案那么优雅。

    【讨论】:

      猜你喜欢
      • 2018-11-10
      • 1970-01-01
      • 2011-08-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-18
      相关资源
      最近更新 更多