python - 在两组布尔和字符串表示之间切换
问题描述
我有 2 个布尔变量:
a = True
b = True
每个都有一些属性,这些属性体现在它们的字符串表示中:
a_str = "a is real"
b_str = "b is surreal"
结果应该:
- 检查是否
a and b
为真,是否为真,输出“ a 是真实的,b 是超现实的” - 检查 only
a
是否为 True,然后输出:“ a is real ” - 检查 only
b
是否为 True,然后输出:“ 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)
是否有更简洁的方法来枚举布尔检查的不同情况?
解决方案
你不能做这样的事情:
' AND '.join(filter(None,[a_str*a,b_str*b,c_str*c]))
推荐阅读
- python - 是否有同时运行多个计时器并在特定事件发生时停止计时器?
- java - 将 Kotlin 扩展方法添加到纯 Java 库
- javascript - 页面刷新/重新加载后不显示警报(Angular v10)
- javascript - Jquery $('#id').find('option').size() vs $('#id option').size() 关于“最大调用堆栈大小”错误
- spring-boot - 如何在 Spring Boot 应用程序中连接后端和前端?
- graphql - 错误:找不到模块“graphql/validation/rules/KnownArgumentNamesRule”
- python - Pythone 错误:pkg_resources.DistributionNotFound:“google-cloud-translate”
- javascript - 当在同一行上使用“process.env”时,DefinePlugin 不会替换 var
- r - R - 根据另一列中的字符串用其他列的值填充数据框的列
- reactjs - 如何在 React 中包含位于 node_modules 文件夹中的脚本