【问题标题】:Operator with two Boolean in pythonpython中带有两个布尔值的运算符
【发布时间】:2020-04-14 12:26:34
【问题描述】:

为什么这两个表达式中的运算符“&”不起作用?

# First, type bool
bool(re.search(r'\d', "4foo"))
>True
# Second, type bool
len("4foo")==4
>True
type(len("4foo")==4)))
>bool

当像这样与运算符“&”一起使用时,我得到False,这不应该是正确的:

# Expected output as this example:
True&True
>True

# The "wrong" output:
 bool(re.search(r'\d', "4foo"))& (len("4foo")==4)
>False

在一个小时后变得疯狂之后,我通过使用我从未预料到的“问题”“解决了”这个问题:

# The "correct" output(transforming a bool type into a bool type something that works but seems stupid...):
 bool(re.search(r'\d', "4foo"))&bool(len("4foo")==4)
>True

解决方案

bool(re.search(r'\d', "4foo")) and len("4foo")==4

【问题讨论】:

  • 这是错误的len("4foo"==4),我猜应该是len("4foo") == 4。无论如何使用 and 而不是 &
  • 在 python 中,当你计算布尔值时,你需要使用 'and' 或 'or' 词来比较。
  • 因为&按位与 运算符,而不是布尔与运算符,在Python 中是and。而且它的优先级不同
  • 另请注意,& 运算符是按位的,并且将 and 运算符用于布尔逻辑
  • 在我的 python shell 中粘贴这个bool(re.search(r'\d', "4foo"))& (len("4foo")==4) 时,我得到了预期的(嗯,有点……)True 结果。但是您仍然应该在这里使用逻辑 and 运算符(并摆脱那些无用的 bool() 调用 - Python 对象都有一个真值)。

标签: python boolean operators


【解决方案1】:

你需要这样做:

& 替换为and

In [638]: bool(re.search(r'\d', "4foo")) and len("4foo")==4                                                                                                                                                 
Out[638]: True

and 测试两个表达式在逻辑上是否为真,而&(与 True/False 值一起使用时)测试两个表达式是否为真。

【讨论】:

  • 由于 and 测试它的操作数是否为真(这只是布尔算术中逻辑“和”的定义),因此您对按位 & 运算符的解释无济于事。
  • 另外,当使用逻辑 and 时,您不需要 bool(something) - Python 对象在布尔上下文中使用时都有真值。
【解决方案2】:

注意括号

len("4foo"==4) ------------> len("4foo")==4

条件

re.search(r'\d', "4foo")and len("4foo")==4 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-11-20
    • 1970-01-01
    • 2019-04-08
    • 2021-01-20
    • 2023-03-08
    • 2015-11-18
    • 1970-01-01
    • 2013-03-02
    相关资源
    最近更新 更多