【问题标题】:Problem in checking the type of the variable [duplicate]检查变量类型的问题[重复]
【发布时间】:2019-09-02 04:53:51
【问题描述】:

我有一个字典列表:

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

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

我试过了:

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

但我得到了这个错误:

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

我也试过了:

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

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

【问题讨论】:

  • 不要使用 liststr 作为变量的名称。

标签: python list class variables types


【解决方案1】:

不要使用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

【讨论】:

    猜你喜欢
    • 2021-11-17
    • 1970-01-01
    • 2015-03-02
    • 2021-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-29
    相关资源
    最近更新 更多