计算列表中有多少空列表

时间:2016-02-24 18:59:07

标签: python list loops

我试图找出列表列表中有多少空列表。 我试过计算多少列表是1的长度,但在python中它给我[]的长度是0但是[3,[]]的长度是2.有没有办法可以计算多少空列表在列表中。

示例列表

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

因此我想将hello列表计为1或计算此总字符串中有多少空列表,即1。

2 个答案:

答案 0 :(得分:7)

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

答案 1 :(得分:0)

脚本:

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

可能不如第一个答案那么优雅。

相关问题