有没有一种简单的方法来确定变量是列表、字典还是其他什么?
当前回答
使用类型()
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__我们可以读
其他回答
可以使用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
type()是比isinstance()更好的解决方案,尤其是对于布尔值:
True和False只是python中表示1和0的关键字。因此
isinstance(True, int)
and
isinstance(False, int)
两者都返回True。两个布尔值都是整数的实例。然而,type()更聪明:
type(True) == int
返回False。
在许多实际情况下,您也可以使用@functools.singledispatch来定义泛型函数(由多个函数组成的函数,对不同类型执行相同的操作),而不是使用类型或isinstance。
换句话说,当您有如下代码时,您可能希望使用它:
def do_something(arg):
if isinstance(arg, int):
... # some code specific to processing integers
if isinstance(arg, str):
... # some code specific to processing strings
if isinstance(arg, list):
... # some code specific to processing lists
... # etc
下面是一个工作原理的小示例:
from functools import singledispatch
@singledispatch
def say_type(arg):
raise NotImplementedError(f"I don't work with {type(arg)}")
@say_type.register
def _(arg: int):
print(f"{arg} is an integer")
@say_type.register
def _(arg: bool):
print(f"{arg} is a boolean")
>>> say_type(0)
0 is an integer
>>> say_type(False)
False is a boolean
>>> say_type(dict())
# long error traceback ending with:
NotImplementedError: I don't work with <class 'dict'>
此外,我们可以使用抽象类同时覆盖几种类型:
from collections.abc import Sequence
@say_type.register
def _(arg: Sequence):
print(f"{arg} is a sequence!")
>>> say_type([0, 1, 2])
[0, 1, 2] is a sequence!
>>> say_type((1, 2, 3))
(1, 2, 3) is a sequence!
使用类型()
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