【问题标题】:How to return None if the list has all values as None else return the truth value in the list in an efficient way如果列表具有所有值,则如何返回 None 否则以有效的方式返回列表中的真值
【发布时间】:2021-09-10 23:23:20
【问题描述】:

我在列表中混合了TrueFalseNone。 如果列表中的所有值都为None,例如ListA=[None, None, None],我将不得不返回None。否则,如果我混合了布尔值和None,例如ListA=[True, True, False, None]。我需要为这个列表返回True,因为它有一个True

还有其他有效的方法来编写这个逻辑吗?

到目前为止我的代码是:

any[listA] if list_A != None then None

【问题讨论】:

  • 类似if all(x is None for x in listA): return None else: return any(listA)
  • 虽然,这可以一次性完成......但这可能不值得
  • any[listA] if list_A != None then None 甚至不是有效的 Python。此外,list_A != None始终为真,因为列表不能等于 None。顺便说一句,ListA = [None, False, False, None] 的预期结果是什么?
  • 谢谢@juanpa.arrivillaga。

标签: python list any


【解决方案1】:

试试这个代码。

is_bool_or_none = lambda some_list: True if (True in [type(element) == bool for element in some_list]) else None
print(is_bool_or_none(your_list_here))

【讨论】:

    【解决方案2】:

    你可以试试下面的代码:

    my_list=[True,None, None, None]
    
    if(any(my_list)):
        print("True")
    else:
        print("None")
    

    如果 my_list 的所有项目都为 None,则返回 None。如果不是,则返回 True。

    到目前为止,使用 any() 是更快、更有效的替代方法。

    【讨论】:

      猜你喜欢
      • 2021-10-15
      • 1970-01-01
      • 2012-10-12
      • 2016-05-03
      • 1970-01-01
      • 2017-10-10
      • 2019-12-23
      • 2023-02-11
      • 1970-01-01
      相关资源
      最近更新 更多