简体   繁体   English

如果列表具有所有值,如何返回 None 作为 None else 以有效的方式返回列表中的真值

[英]How to return None if the list has all values as None else return the truth value in the list in an efficient way

I have a mix of True , False , None in a list.我在列表中混合了TrueFalseNone If I have all values as None in the list eg ListA=[None, None, None] I will have to return None .如果列表中的所有值都为None ,例如ListA=[None, None, None]我将不得不返回None Otherwise, If I have a mix of boolean values and None eg ListA=[True, True, False, None] .否则,如果我混合了布尔值和None例如ListA=[True, True, False, None] I need to return True for this list because it has one True .我需要为此列表返回True ,因为它有一个True

Is there another efficient way to write this logic?有没有另一种有效的方法来编写这个逻辑?

my code so far is:到目前为止我的代码是:

any[listA] if list_A != None then None

You can try the below code:你可以试试下面的代码:

my_list=[True,None, None, None]

if(any(my_list)):
    print("True")
else:
    print("None")

returns None if all items of my_list are None.if not returns True.如果 my_list 的所有项目都为 None,则返回 None。如果不是,则返回 True。

Using any() is by far the faster and effective alternative.使用 any() 是迄今为止更快、更有效的替代方法。

Try this code.试试这个代码。

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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM