有没有更干净的方法可以在Python中编写此布尔比较?

Cod*_*T96 1 python if-statement boolean-expression conditional-statements python-3.x

此作业的说明为:

我们传入2个布尔输入,寒冷和多雨。

您应该根据这些输入输出一个字符串:(“冷”或“暖”)“和”(“多雨”或“干”)。

(“冷”或“暖”)表示您应根据输入的布尔值使用两个单词中的一个。

例如False,True =“温暖多雨”

我输入的代码是:

# Get our boolean values from the command line
import sys
isCold= sys.argv[1] == 'True'
isRainy= sys.argv[2] == 'True'

# Your code goes here

condition = ""
if (isCold):
  condition += "cold"
else:
  condition += "warm"

if (isRainy):
  condition += " and rainy"
else:
  condition += " and dry"

print(condition)
Run Code Online (Sandbox Code Playgroud)

该代码是正确的并且可以输出预期的结果,但是我想知道是否有一种更干净的方式编写此代码?我感觉好像有,但我不太清楚。

cdh*_*wie 5

您可以将条件表达式与Python 3.6的f字符串结合使用,以单行代码构建字符串:

condition = f"{'cold' if isCold else 'warm'} and {'rainy' if isRainy else 'dry'}"
Run Code Online (Sandbox Code Playgroud)

在Python 2中,%字符串格式运算符也可以正常工作:

condition = "%s and %s" % (
    'cold' if isCold else 'warm',
    'rainy' if isRainy else 'dry'
)
Run Code Online (Sandbox Code Playgroud)