【问题标题】:Creating an OR logic function with a list composed of bool functions Python使用由布尔函数 Python 组成的列表创建 OR 逻辑函数
【发布时间】:2022-01-06 16:31:54
【问题描述】:

我想编写一个函数来检查True boolena 语句是否在all_vals 内,如果有True 值,那么代码将yes,如果不是,代码将输出no,本质上是创建或声明。下面的代码不起作用我将如何修改它以便获得下面的预期输出?

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

【问题讨论】:

标签: python for-loop math boolean logic


【解决方案1】:

您需要 if True in x: 而不是:if True in all_vals:,如下所示:

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

【讨论】:

  • 您关于“大幅缩短代码”的建议使其更难阅读和理解。此外,使用lambda 定义命名函数是违反风格指南的:PEP 8 -- Style Guide for Python Code
  • @Stef 我同意它只是为那些喜欢单线的人准备的。这就是为什么我也给出了扩展版本。
【解决方案2】:
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])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-15
    • 1970-01-01
    相关资源
    最近更新 更多