python - Python 3.6 - “NoneType”测试失败
问题描述
我正在从sqlite3
数据库中读取并过滤掉NoneType
,因为我只想要不是的值 None
。我尝试了这里建议的两种方法,结果相同。这让我认为下面的 if 语句是正确的,但我错过了一些更基本的东西。任何建议表示赞赏。
从数据库中读取
conn.commit()
c.execute("SELECT tact FROM LineOEE03 ORDER BY tact DESC LIMIT 1")
current_tact = c.fetchone()
无类型测试
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”
- 如果我
not None
在我的 中专门标记类型,为什么会出现此错误if-statement
? - 这样做的正确方法是什么,例如当值是
None
我可以分配一个预定义的值?
解决方案
您可以添加一个额外的测试来检查列表中的第一项是否不是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
推荐阅读
- discord - 向服务器的所有成员添加角色的代码
- statistics - 我想知道我所做的统计分析是否有意义
- elasticsearch - 在弹性搜索上不起作用的术语
- android - 未处理的异常:键入“列表”
' 不是 'String' 类型的子类型 无法获取 json 数据 - swift - 视图中的 AVFoundation 摄像头
- azure - Azure 与服务总线主题的集成
- clojure - cider-connect-clj 无法连接到 nrepl.server/start-server
- excel - 将标题转换为单元格并加入
- spring - 创建 bean 'kafkaMessageChannelBinder' 定义的 org.springframework.cloud.stream.binder.kafka.config.KafkaBinderConfiguration 时出错:
- keras - 无效参数:在空标签后面看到一个非空标签(索引 >= num_classes - 1)