python - 检查变量类型的问题
问题描述
我有一个字典列表:
list=[{'step' : '1' , 'name' : 'A'}]
我想在 if 条件下检查 step 键的值的类型。
我努力了 :
if (x=isinstance(list[0]['step'],str)) :
但我得到了这个错误:
TypeError: isinstance() arg 2 必须是类型或类型的元组
我也试过:
list[0]['step'].__class__ == str
但也有错误。正确的方法是什么?
解决方案
不要list
用作变量名,因为它已经被 python 用于数据类型列表。如果您更改list
为mylist
,则检查有效。
In [1]: mylist=[{'step' : '1' , 'name' : 'A'}]
In [2]: mylist
Out[2]: [{'name': 'A', 'step': '1'}]
In [3]: if isinstance(mylist[0]["step"], str):
...: print(True)
...:
True
推荐阅读
- c# - 如何将自动显示面板放在 LibVLCSharp.WPF.VideoView 上?
- node.js - 如何在 node.js 上获取类的属性及其方法
- ckeditor - 覆盖 CKEditor 5 内容编辑 css
- npm - 在 bitbucket-pipeline 中运行 nuxt.js 会引发“未定义”错误
- c# - 我决定将两个场景都加载到层次结构中,因为在它们之间引用变量更容易。我怎样才能重新开始一个新游戏?
- python-3.x - 通过python将.mat文件扩展名图像转换为.jpg
- python - 从响应中获取空文件并且无法将文件保存在 django 模型类中
- linux - 如何将目录中的多个 .dav 文件转换为 .mp4
- c# - 类型未标记为可序列化
- java - 如何使用类的字符串属性在 java 中引用该类?