Python:如何检查嵌套列表是否基本为空? [英] Python: How to check if a nested list is essentially empty?

查看:112
本文介绍了Python:如何检查嵌套列表是否基本为空?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有Python方式检查列表(带有元素和列表的嵌套列表)本质上是空的?我这里所说的空白是指该列表可能包含元素,但这些元素也是空列表.

Is there a Pythonic way to check if a list (a nested list with elements & lists) is essentially empty? What I mean by empty here is that the list might have elements, but those are also empty lists.

检查空列表的Python方法仅适用于平面列表:

The Pythonic way to check an empty list works only on a flat list:

alist = []
if not alist:
    print("Empty list!")

例如,以下所有列表应为空:

For example, all the following lists should be positive for emptiness:

alist = []
blist = [alist]               # [[]]
clist = [alist, alist, alist] # [[], [], []]
dlist = [blist]               # [[[]]]

推荐答案

我结合了 Ants Aasma Stephan202 all(map())isinstance()的使用,形成以下解决方案. all([])返回True,并且函数依赖于此行为.我认为它既有优势,又有优势,因为它不依赖于TypeError异常.

I have combined the use of isinstance() by Ants Aasma and all(map()) by Stephan202, to form the following solution. all([]) returns True and the function relies on this behaviour. I think it has the best of both and is better since it does not rely on the TypeError exception.

def isListEmpty(inList):
    if isinstance(inList, list): # Is a list
        return all( map(isListEmpty, inList) )
    return False # Not a list

这篇关于Python:如何检查嵌套列表是否基本为空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆