首页 > 解决方案 > 检查变量类型的问题

问题描述

我有一个字典列表:

list=[{'step' : '1' , 'name' : 'A'}]

我想在 if 条件下检查 step 键的值的类型。

我努力了 :

if (x=isinstance(list[0]['step'],str)) :

但我得到了这个错误:

TypeError: isinstance() arg 2 必须是类型或类型的元组

我也试过:

list[0]['step'].__class__ == str

但也有错误。正确的方法是什么?

标签: pythonlistclassvariablestypes

解决方案


不要list用作变量名,因为它已经被 python 用于数据类型列表。如果您更改listmylist,则检查有效。

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

推荐阅读