【问题标题】:How to find out if value1 AND value2 AND value3 are < value4?如何找出 value1 AND value2 AND value3 是否 < value4?
【发布时间】:2020-08-07 16:13:29
【问题描述】:

我正试图在 python 中测试多个值。假设我有

value1 = 7
value2 = 2
value3 = 4

我想知道它们是否小于 10。只有一个值,显然就像

value1 < 10

导致True。看看我如何在自然语言中使用and,我会假设对所有人进行测试很简单

value1 and value2 and value3 < 10

它确实导致True。但是,如果我更改value1 = 20,上面仍然是正确的,虽然它显然是False。因此,除非我在 python 中发现了一个巨大的错误,否则我显然不明白and 是如何工作的,不幸的是,only docs I can find 对我没有多大帮助(在文档中很难找到任何东西,搜索@987654331 @...)。

(value1 < 10) and (value2 < 10) and (value3 < 10)

按预期工作,但看看它,它应该与我的第一个版本相同或

(value1 and value2 and value3) < 10    

这也给了我一个错误的True

【问题讨论】:

  • 最后一次尝试 ((value1 and value2 and value3) &lt; 10) 给出了错误的 True,因为如果整数不为零,则该整数为真。因此,括号内的陈述为真。 True 小于 10。因此,Python 返回True 是正确的。使用max([value1,value2,value3])&lt;10查看是否所有值都小于10。如果最大的小于10,则都小于10。
  • and 运算符接受两个布尔值并将它们组合起来。所以像(20 and 10) &lt; 15 这样的东西没什么意义。解析为(True and True) &lt; 15,然后解析为True &lt; 15,后者也解析为True

标签: python logical-operators


【解决方案1】:

我很乐意回答你的问题。

使用“if”语句时,您必须在布尔表达式之间放置“and”,即,如果您测试像 if someVariable 这样的语句并且 someVariable 的值不是 None,那么您总是会得到一个“真”的输出,所以试试这个:

if val1 < 10 and val2<10 and val3<10:
    <code body>

请允许我解释一下为什么这有效,而 if (val1 and ...) &lt; 10 无效。

这是因为,例如,表达式 val1 and val2 将始终产生 True,只要两个变量的值都不是 None,所以当您使用表达式 val1 and val2 ... 时,您本质上是只是得到答案:True &lt; 10 产生True

我希望这个答案对您有所帮助。 :D

【讨论】:

  • if something and something: 我知道并使用,因此我想我可以将其简化为我的第一个想法,因为 if 语句暗示(对我来说?)and 的工作方式类似于书面语言。
【解决方案2】:

关于andoperator 的工作原理已经有了很好的解释,所以我只想添加一个快速解决方案来测试多个数字是否小于另一个数字:

if max(value1, value2, value3) < value4:
    print("True")

这是可行的,因为内置的max函数返回最大数量的给定值。它也可以使用列表或元组作为输入:

number = [value1, value2, value3]
if max(numbers) < value4:
    print("True")

【讨论】:

    【解决方案3】:

    Python and 运算符有一点你偶然发现的特殊性:

    val = 5
    print(1 and val)
    print(2 and val)
    print(0 and val)
    print(-1 and val)
    print(-2 and val)
    

    输出:

    5
    5
    0
    5
    5
    

    所以,在 Python 中,and 直接返回 0,如果第一个表达式被评估为 0,否则它返回第二个表达式!

    因此,在您的情况下,val1 and val2 and val3 将返回 val3,因为其他人是 non-zero

    【讨论】:

    • 确实很特别。是否有一些可用的文档或 PEP?
    • 您在问题中提到的documentation,实际上是在谈论这个。
    【解决方案4】:

    Python 提供了有用的内置函数 anyall,它们允许编写这样的可读代码:

    if all(v < 10 for v in (value1, value2, value3)):
        ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-24
      • 1970-01-01
      • 2010-09-18
      • 1970-01-01
      • 2020-12-05
      相关资源
      最近更新 更多