【问题标题】:Check if any element in list is empty/'not a number' (Python)检查列表中的任何元素是否为空/“不是数字”(Python)
【发布时间】:2020-06-20 13:34:31
【问题描述】:

我想使用 if 语句来检查列表是否包含空元素。执行以下操作的行:

list1 = [1,2,[],2]
list2 = [1,2,1,2]

>>>list1 'contains empty element'
True

>>>list2 'contains empty element'
False

我非常关心运行时间。

非常感谢您的帮助!

【问题讨论】:

  • 0 是“空元素”吗?和None?如果是这样,只需使用all
  • 谢谢,我不知道 all()。但是 0 应该是一个“非空”元素/一个数字。如果所有元素都为 0,all() 是否返回 False?该列表永远不会包含 None 的

标签: python-3.x list if-statement


【解决方案1】:

你可以使用:

any(e == [] for e in my_list)

或:

[] in my_list

如果你想使用if-statement

def check(my_list):
    for e in my_list:
        if e == []:
            return True
    return False

print(check(list1))
print(check(list2))

输出:

True
False

或者你可以使用三元运算符:

True if [] in my_list else False

【讨论】:

    【解决方案2】:

    如果你想要任何数字和任何布尔值为 True 的元素,试试这个:

    def any_empty(lst):
        return not all(isinstance(x, int) or x for x in lst)
    
    print(any_empty([0, 1, 2, 3, ["Foo"]]))
    print(any_empty([ () ]))
    print(any_empty([ [] ]))
    

    输出:

    False
    True
    True
    

    【讨论】:

      【解决方案3】:

      请检查一下。

      list1 = [1,2,[],2]
      list2 = [1,2,1,2]
      
      
      if [] in list1:
          print("List 1 contains empty list ? ", ([] in list1))
      
      if [] in list2:
          print("List 2 contains empty list ? ", ([] in list2))
      
      

      或者

      print("List 1 contains empty list ? ", ([] in list1))
      print("List 2 contains empty list ? ", ([] in list2))
      
      

      【讨论】:

        【解决方案4】:

        这里:

        all([not (isinstance(x, list) and not x) for x in list1])
        

        【讨论】:

          猜你喜欢
          • 2011-11-03
          • 1970-01-01
          • 1970-01-01
          • 2014-09-19
          • 2015-09-15
          • 1970-01-01
          • 2017-09-05
          • 1970-01-01
          相关资源
          最近更新 更多