使用由 bool 函数组成的列表创建 OR 逻辑函数 Python

Creating an OR logic function with a list composed of bool functions Python

我想编写一个函数来检查 True boolena 语句是否在 all_vals 内,如果存在 True 值,则代码将 yes 如果不存在代码将输出 no,本质上是创建一个 or 语句。下面的代码不起作用,我该如何修改它才能获得下面的预期输出?

def vals(all_vals):
    for x in all_vals:
        if True in all_vals:
            print('yes')
        else:
            print('no')


a = [True, True, True]
b = [True, False, True, True, False]
c = [False, False]
d = [True, False]

vals([a,b,c,d]) 

预期输出:

yes
yes
no
yes
def vals(all_vals):
    for x in all_vals:
        if True in x: # <--- Your typo here
            print("yes")
        else:
            print("no")


a = [True, True, True]
b = [True, False, True, True, False]
c = [False, False]
d = [True, False]

vals([a, b, c, d])

而不是:if True in all_vals: 你需要 if True in x: 这样的:

def vals(all_vals):
    for x in all_vals:
        if True in x:
            print('yes')
        else:
            print('no')


a = [True, True, True]
b = [True, False, True, True, False]
c = [False, False]
d = [True, False]

vals([a,b,c,d]) 

您也可以通过以下方式来缩短代码:

vals = lambda all_vals: print("\n".join(['yes' if True in i else 'no' for i in all_vals]))

a = [True, True, True]
b = [True, False, True, True, False]
c = [False, False]
d = [True, False]

vals([a,b,c,d]) 

输出:

yes
yes
no
yes