![](/img/trans.png)
[英]How to check if, in a given list of objects, each different type of object is comparable?
[英]A different way to check the type of a list
list = [1,2,3]
print(type(list) == list) # Prints False
除了更改列表名称之外,还有其他方法可以检查此列表的类型吗? (因为我已经在我的代码中多次引用了 list 变量,并且很难更改所有这些变量。)
您的代码正确地返回False
,因为您用列表替换了 list 的原始含义。 您不应该使用 Python 内置函数的名称作为变量名称。
因此,更改您的列表名称,它将按预期工作。
如果为时已晚,正如您在编辑问题中所建议的那样,您仍然可以通过以下方式访问原始list
:
list = [1,2,3]
print(type(list) == __builtins__.list)
# True
或者,更推荐的方法是使用isinstance
而不是type(...) == ...
:
print(isinstance(list, __builtins__.list))
# True
这是因为您正在隐藏内置list
l = [1,2,3]
print(type(l) == list) # True
type(list)
给出<class 'list'>
,它不是[1,2,3]
。
您可以使用@ThierryLathuille 建议的选项之一,但最佳做法是重命名list
变量,您不应使用内置名称作为变量名称。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.