检查字符串列表和列表是否为空

时间:2019-02-14 16:44:06

标签: python

如何检查此列表是否为空?

l = ['',['']]

我尝试了如何查找嵌套列表是否为空的解决方案。但他们都不起作用。

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

5 个答案:

答案 0 :(得分:1)

在递归检查列表项之前,应先检查列表是否虚假/空。您还可以避免使用TrueFalse运算符来显式返回andor

def isListEmpty(inList):
    return inList == '' or isinstance(inList, list) and (not inList or all(map(isListEmpty, inList)))

演示:https://repl.it/repls/AccurateSmallOutcome

答案 1 :(得分:0)

对于实际上为空的列表,该函数应仅返回True。

def isListEmpty(inList):
    if isinstance(inList, list): # Is a list
        if len(inList) == 0:
            return True
        else:
            return all(map(isListEmpty, inList))
    return False # Not a list

答案 2 :(得分:0)

l实际上不是空的。但是在这种情况下,此代码应该可以工作:

l = ['',['']]
def isListEmpty(inList):
    for char in inList:   
        if char == '' or ['']:
            return True
        else:
            return False
            break

print(isListEmpty(l))

答案 3 :(得分:0)

您可以对any使用简单的递归方法。使用any可以确保找到非空项目后递归搜索结束

>>> def is_non_empty_list (l):
...     return any(is_non_empty_list(e) if isinstance(e, list) else e for e in l)
... 
>>> def is_empty_list (l):
...     return not is_non_empty_list(l)
... 
>>> is_empty_list(['', ['']])
True
>>> is_empty_list(['', ['a']])
False
>>> 

答案 4 :(得分:-1)

尝试一下

l = [' ',[ ]]
def isListEmpty(thisList):
  for el in thisList:
    if (len(el)==0 and type(el)==list):
      print('empty') # Or whatever you want to do if you encounter an empty list

isListEmpty(l)

如果您遇到任何问题,请在下面评论