سؤال

What is the most effective way to check if a list contains only empty values (not if a list is empty, but a list of empty elements)? I am using the famously pythonic implicit booleaness method in a for loop:

def checkEmpty(lst):
    for element in lst:
        if element:
            return False
            break
    else:
        return True

Anything better around?

هل كانت مفيدة؟

المحلول

if not any(lst):
    # ...

Should work. any() returns True if any element of the iterable it is passed evaluates True. Equivalent to:

def my_any(iterable):
    for i in iterable:
        if i:
            return True
    return False

نصائح أخرى

len([i for i in lst if i]) == 0

Using all:

   if all(item is not None for i in list):
      return True
    else:
      return False
>>> l = ['', '', '', '']
>>> bool([_ for _ in l if _])
False
>>> l = ['', '', '', '', 1]
>>> bool([_ for _ in l if _])
True
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top