首页 > 解决方案 > 在两组布尔和字符串表示之间切换

问题描述

我有 2 个布尔变量:

a = True
b = True

每个都有一些属性,这些属性体现在它们的字符串表示中:

a_str = "a is real"
b_str = "b is surreal"

结果应该:

我已经尝试了以下方法并且它有效,但引出不同的 if-elifs 相当冗长,即

a = True
b = True

a_str = "a is real"
b_str = "b is surreal"

if a and b:
    print(f"{a_str} AND {b_str}")
elif a:
    print(a_str)
elif b:
    print(b_str)

尤其是 如果有一个新变量c,例如

a = True
b = True
c = True

a_str = "a is real"
b_str = "b is surreal"
c_str = "c is cereal"

if a and b and c:
    print(f"{a_str} AND {b_str} AND {c_str")
elif a and b:
     print(f"{a_str} AND {b_str}")
elif a and c:
     print(f"{a_str} AND {b_str}")
elif b and c:
     print(f"{b_str} AND {c_str}")
elif a:
     print(a_str)
elif b:
     print(b_str)
elif c:
     print(c_str)

是否有更简洁的方法来枚举布尔检查的不同情况?

标签: pythonstringif-statementbooleancombinations

解决方案


你不能做这样的事情:

' AND '.join(filter(None,[a_str*a,b_str*b,c_str*c]))

推荐阅读