【问题标题】:Attempting to check if a list isn't empty AND some other condition within the same if statement尝试检查列表是否为空以及同一 if 语句中的某些其他条件
【发布时间】:2018-06-23 11:35:34
【问题描述】:

解释这一点的最简单方法是举一个简单的例子:

x = [0]

f = 4
if (x) & (f < 6):
    print("yes")

这个想法很简单,检查列表是否包含任何内容以及其他变量是否小于某个数字。

解决方案产生以下错误,我不完全确定解决方案是什么。

TypeError: unsupported operand type(s) for &: 'list' and 'bool'

【问题讨论】:

  • 在 Python 中,&amp; 代表位与,逻辑与由and 表示。

标签: python list if-statement typeerror


【解决方案1】:

&amp; 不是 Python 中的逻辑“与”运算符,而是bitwise and operator。相反,您应该使用逻辑“与”运算符,即and

if (x) and (f < 6):
    print("yes")

【讨论】:

    【解决方案2】:

    &amp; 是“按位与”运算符,而and 是逻辑与运算符。

    正确的if语句如下:

    if x and f < 6:
        print("yes")
    

    请注意,此处不需要括号。此外,在 Python 中,非空列表被评估为True,这就是为什么您可以使用x 而不是len(x) &gt; 0,这也是正确的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-17
      • 2020-10-01
      • 2016-03-03
      • 1970-01-01
      • 1970-01-01
      • 2017-07-08
      相关资源
      最近更新 更多