【问题标题】:Most concise way to check whether a list is empty or contains only None?检查列表是否为空或仅包含无的最简洁方法?
【发布时间】:2010-11-19 05:55:00
【问题描述】:

检查列表是否为空或仅包含无的最简洁方法?

我知道我可以测试:

if MyList:
    pass

和:

if not MyList:
    pass

但是如果列表有一个项目(或多个项目),但这些项目是无:

MyList = [None, None, None]
if ???:
    pass

【问题讨论】:

    标签: python list types


    【解决方案1】:

    如果您关心列表中评估为 true 的元素:

    if mylist and filter(None, mylist):
        print "List is not empty and contains some true values"
    else:
        print "Either list is empty, or it contains no true values"
    

    如果要严格检查None,请在上面的if 语句中使用filter(lambda x: x is not None, mylist) 而不是filter(None, mylist)

    【讨论】:

      【解决方案2】:

      一种方法是使用all 和列表推导:

      if all(e is None for e in myList):
          print('all empty or None')
      

      这也适用于空列表。更一般地,要测试列表是否仅包含评估为 False 的内容,您可以使用 any

      if not any(myList):
          print('all empty or evaluating to False')
      

      【讨论】:

      • 这可能更有效,是的,但使用== 并没有错误
      【解决方案3】:

      您可以使用all() 函数来测试是否所有元素都为None:

      a = []
      b = [None, None, None]
      all(e is None for e in a) # True
      all(e is None for e in b) # True
      

      【讨论】:

        【解决方案4】:

        您可以直接将列表与==进行比较:

        if x == [None,None,None]:
        
        if x == [1,2,3]
        

        【讨论】:

          猜你喜欢
          • 2016-03-05
          • 2022-09-24
          • 2011-04-03
          • 2017-09-01
          • 2011-12-28
          • 1970-01-01
          • 1970-01-01
          • 2011-08-08
          • 1970-01-01
          相关资源
          最近更新 更多