[英]Getting Boolean value from greater than, less than, and equal to without a bunch of if statements?
I have two lists compared for a game to see if one is greater/less or if they are equal.我为一款游戏比较了两个列表,以查看一个列表是更大还是更少,或者它们是否相等。
If I use <=
or >=
the boolean value will print a win/lose.如果我使用
<=
或>=
布尔值将打印赢/输。 But if they are equal, the value will still be either win/lose.但如果它们相等,则价值仍然是赢/输。 Is there a way to print "tie" without a bunch of
if
statements?有没有办法在没有一堆
if
语句的情况下打印“领带”?
What I have now is this:我现在拥有的是:
totalA = [5, 5, 5]
totalB = [5, 5, 5]
grandtotal = sum(totalA) <= sum(totalB)
if grandtotal == True:
print("Win")
else:
print("Lose")
If you have three possible outcomes, that's not a boolean value, since a boolean value by definition only has two possibilities.如果您有三种可能的结果,那不是布尔值,因为根据定义,布尔值只有两种可能性。 Capturing three possibilities with booleans requires at least two booleans (eg
"Win" if a < b else "Lose" if b < a else "Tie"
).用布尔值捕获三种可能性需要至少两个布尔值(例如,
"Win" if a < b else "Lose" if b < a else "Tie"
)。 But if you want to do it with no if
statements at all, there's a way!但是,如果您想在完全不使用
if
语句的情况下执行此操作,则有一种方法!
Create a mathematical comparison function that'll return a result from the set -1, 0, 1
based on which of the two numbers is bigger, and then map those results to the desired strings.创建一个数学比较函数,该函数将根据两个数字中的哪个更大,从集合
-1, 0, 1
返回一个结果,然后将这些结果映射到所需的字符串。
print({
1: "Win",
0: "Tie",
-1: "Lose",
}[(sum(totalB) - sum(totalA)) // (abs(sum(totalB) - sum(totalA)) or 1)])
Putting it into a function (and adding a bit of int
conversion to make it handle float
inputs as well):将它放入一个函数中(并添加一些
int
转换以使其也处理float
输入):
>>> def print_result(totalA, totalB):
... delta = sum(totalB) - sum(totalA)
... print({
... 1: "Win",
... 0: "Tie",
... -1: "Lose",
... }[int(delta // (abs(delta) or 1))])
...
>>> print_result([5, 5, 5], [5, 5, 5])
Tie
>>> print_result([1, 2, 3], [2, 3, 4])
Win
>>> print_result([3, 4, 5], [2, 3, 4])
Lose
>>> print_result([5, 5, 5], [5, 5, 5.0])
Tie
>>> print_result([5, 5.1, 5], [5, 5, 5.0])
Lose
>>> print_result([5, 5.1, 5], [5, 5.2, 5.0])
Win
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.