Python 计算一个列表中有多少个空列表
我试图找出列表中有多少空列表。 我试图计算长度为1的列表的数量,但在python中,Python 计算一个列表中有多少个空列表,python,list,loops,Python,List,Loops,我试图找出列表中有多少空列表。 我试图计算长度为1的列表的数量,但在python中,[]的长度为0,而[3,[]]的长度为2。有没有一种方法可以让我计算一个列表中有多少个空列表 示例列表 [[1,[2,3,4],['hello',[]],['weather',['hot','rainy','sunny','cold']]]] 因此,我想将hello列表计算为1,或者计算此总字符串中有多少空列表,即1。脚本: def count_empties(lst, is_outer_list=True):
[]
的长度为0,而[3,[]]
的长度为2。有没有一种方法可以让我计算一个列表中有多少个空列表
示例列表
[[1,[2,3,4],['hello',[]],['weather',['hot','rainy','sunny','cold']]]]
因此,我想将hello列表计算为1,或者计算此总字符串中有多少空列表,即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
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
可能没有第一个答案那么优雅。正如我的示例列表所示。[[content,[more content],[content,[more content],[content,[more content],[content,[more content]]您的示例列表有点不清楚:缺少2
]
。我认为您的示例列表应该是[[1,2,3,4],['hello',[]],['weather',['hot','rain','sunny','cold']
。是否正确?@JRazor根据OP上面的评论,PM 2Ring很可能是正确的。这意味着您的编辑与OP的意图冲突。