【问题标题】:Python 3.6 - 'NoneType' test failsPython 3.6 - “NoneType”测试失败
【发布时间】:2019-02-03 20:13:50
【问题描述】:

我正在读取 sqlite3 数据库并过滤掉 NoneType,因为我只想要 不是 None 的值。我尝试了建议here 的两种方法,结果相同。这让我认为下面的 if 语句是正确的,但我错过了一些更基本的东西。任何建议表示赞赏。

从数据库中读取

        conn.commit()
        c.execute("SELECT tact FROM LineOEE03 ORDER BY tact DESC LIMIT 1")
        current_tact = c.fetchone()

NoneType 测试

        if current_tact is not None:
            current_tact = int(current_tact[0])
        else:
            current_tact = 60

错误

current_tact = int(current_tact[0])

TypeError: int() 参数必须是字符串、类似字节的对象或数字,而不是 'NoneType'

  • 如果我在if-statement 中专门标记not None 类型,为什么会出现此错误?
  • 这样做的正确方法是什么,例如当值为None 时,我可以分配一个预定义的值?

【问题讨论】:

  • current_tact = [None](或包含None 作为第一个元素的列表/元组)?
  • 似乎没有在 current_tact 中存在。
  • 试试print(current_tact),你会立即发现问题。
  • @hiroprotagonist,绝对正确。输出为:(None,) 感谢您引导我朝着正确的方向前进,Aran-Fey,这是我的一个非常基本的错误。

标签: python python-3.x


【解决方案1】:

您可以添加一个额外的测试来检查列表中的第一项是否不是None,这就是您实际尝试转换为整数的内容:

if current_tact is not None and current_tact[0] is not None:
    current_tact = int(current_tact[0])

或使用try-except 块来避免测试:

try:
    current_tact = int(current_tact[0])
except TypeError:
    current_tact = 60

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-18
    • 2020-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-29
    相关资源
    最近更新 更多