检查变量是否为列表的最佳方法是什么?

检查变量是否为列表的最佳方法是什么?

问题描述:

我发现了这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 of x is either list or has list as a parent class (lets ignore ABCs for simplicity etc);
  • type(x) is list checks if the type of x is precisely list;
  • 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
  • 一样是x
  • type(x) is list:恰恰是xlist,而不是的子类
  • type(x) == list:是x的列表,或使用元类魔术来伪装成list的其他某种类型.
  • isinstance(x, list): is x like a list
  • type(x) is list: is x precisely a list and not a sub class
  • type(x) == list: is x a list, or some other type using metaclass magic to masquerade as a list.