有没有一种简单的方法来确定变量是列表、字典还是其他什么?


当前回答

value = 12
print(type(value)) # will return <class 'int'> (means integer)

或者你可以这样做

value = 12
print(type(value) == int) # will return true

其他回答

使用类型()

x='hello this is a string'
print(type(x))

输出

<class 'str'>

要仅提取str,请使用

x='this is a string'
print(type(x).__name__)#you can use__name__to find class

输出

str

如果使用类型(变量)__name__我们可以读

为了完整起见,isinstance不适用于非实例的子类型的类型检查。虽然这很有道理,但没有一个答案(包括公认的答案)涵盖了这一点。请使用issubclass。

>>> class a(list):
...   pass
... 
>>> isinstance(a, list)
False
>>> issubclass(a, list)
True

可以使用type()或isinstance()。

>>> type([]) is list
True

请注意,通过在当前作用域中分配同名变量,可以删除列表或任何其他类型。

>>> the_d = {}
>>> t = lambda x: "aight" if type(x) is dict else "NOPE"
>>> t(the_d) 'aight'
>>> dict = "dude."
>>> t(the_d) 'NOPE'

上面我们看到dict被重新分配给一个字符串,因此测试:

type({}) is dict

…失败。

要解决此问题并更谨慎地使用type():

>>> import __builtin__
>>> the_d = {}
>>> type({}) is dict
True
>>> dict =""
>>> type({}) is dict
False
>>> type({}) is __builtin__.dict
True

使用类型():

>>> a = []
>>> type(a)
<type 'list'>
>>> f = ()
>>> type(f)
<type 'tuple'>

通常,您可以从具有类名的对象中提取字符串,

str_class = object.__class__.__name__

并将其用于比较,

if str_class == 'dict':
    # blablabla..
elif str_class == 'customclass':
    # blebleble..