检查变量是否为列表的最佳方法是什么?
我发现了这3种检查方法,但是我不知道哪种方法最好:
I found this 3 ways to check it, but I don't know which of them is the best:
x = ['Bla', 'Bla', 'Bla', 'etc']
if isinstance(a, list): print('Perfect!')
if type(a) is list: print('Incredible!')
if type(a) == type([]): print('Awesome!')
其中哪个更好?
此外,我可以使用以下方式检查 x 是否为字符串,元组,字典,int,float等吗?如果可能的话,在前两种方法中,我是否必须将列表转换为元组,字符串,字典,int,float等(否?),但是在第三种方法中?我必须使用(),{},'',以及int和float还要使用什么?
Also, Can I use these ways to check whether an x is a string, tuple, dictionary, int, float, etc? If this is possible, in the first two methods do I have to convert a list to a tuple, string, dictionary, int, float, etc (no?), but in the third? I have to use (), {}, '', and what more for int and float?
这些都表达不同的内容,因此,实际上,这完全取决于您希望实现的目标:
These all express different things, so really it depends on exactly what you wish to achieve:
-
isinstance(x, list)
检查x
的类型是list
还是以list
作为父类(为简单起见,请忽略ABC); -
type(x) is list
检查x
的类型是否恰好是list
; -
type(x) == list
检查类型是否相等,这与元类型可以覆盖__eq__
的类型相同是不同的
-
isinstance(x, list)
check if the type ofx
is eitherlist
or haslist
as a parent class (lets ignore ABCs for simplicity etc); -
type(x) is list
checks if the type ofx
is preciselylist
; -
type(x) == list
checks for equality of types, which is not the same as being identical types as the metaclass could conceivably override__eq__
因此,为了表达以下内容:
So in order they express the following:
-
isinstance(x, list)
:像list
一样是 -
type(x) is list
:恰恰是x
是list
,而不是的子类 -
type(x) == list
:是x
的列表,或使用元类魔术来伪装成list
的其他某种类型.
x
-
isinstance(x, list)
: isx
like alist
-
type(x) is list
: isx
precisely alist
and not a sub class -
type(x) == list
: isx
a list, or some other type using metaclass magic to masquerade as alist
.