检查列表的总和是否等于两个值之一

时间:2020-02-18 19:52:42

标签: python list

我有一个对或错的列表。我想知道他们是否都是对还是错。

我的代码:

list1 = [False, True,False,False,True]
list2 = [False, True,False,True]
list3 = [False, False,False]
list4 = [True, True,True, True,True]

if sum(list1)==len(list1)|0:
    print("Yes! all are either True or False")
else:
    print("Not satisfied")

如果所有代码均为True,但如果所有代码均为False,我的代码就可以正常工作。如何检查是否全部为假

四个列表的预期输出:

list1 >> Not satisfied
list2 >> Not satisfied
list3 >> Yes! all are either True or False
list4 >> Yes! all are either True or False

1 个答案:

答案 0 :(得分:3)

在这种情况下,您可以使用内置的all()any()

for lst in [list1, list2, list3, list4]:
    if all(lst) or not any(lst):   # if it isn't true that any are true, then all must be False
        print("Yes! all are either True or False")
    else:
        print("Not satisfied")

输出:

Not satisfied
Not satisfied
Yes! all are either True or False
Yes! all are either True or False
相关问题