检查python中的type == list
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26544091/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Checking if type == list in python
提问by Benjamin Lindqvist
I may be having a brain fart here, but I really can't figure out what's wrong with my code:
我可能在这里放屁了,但我真的不知道我的代码有什么问题:
for key in tmpDict:
print type(tmpDict[key])
time.sleep(1)
if(type(tmpDict[key])==list):
print 'this is never visible'
break
the output is <type 'list'>but the if statement never triggers. Can anyone spot my error here?
输出是<type 'list'>但 if 语句永远不会触发。任何人都可以在这里发现我的错误吗?
采纳答案by Ffisegydd
Your issue is that you have re-defined listas a variable previously in your code. This means that when you do type(tmpDict[key])==listif will return Falsebecause they aren't equal.
您的问题是您list之前在代码中重新定义为变量。这意味着当你执行type(tmpDict[key])==listif 会返回,False因为它们不相等。
That being said, you should instead use isinstance(tmpDict[key], list)when testing the type of something, this won't avoid the problem of overwriting listbut is a more Pythonic way of checking the type.
话虽如此,您应该isinstance(tmpDict[key], list)在测试某事物的类型时使用它,这不会避免覆盖问题,list而是一种更 Pythonic 的检查类型的方式。
回答by d-coder
You should try using isinstance()
你应该尝试使用 isinstance()
if isinstance(object, list):
## DO what you want
In your case
在你的情况下
if isinstance(tmpDict[key], list):
## DO SOMETHING
To elaborate:
详细说明:
x = [1,2,3]
if type(x) == list():
print "This wont work"
if type(x) == list: ## one of the way to see if it's list
print "this will work"
if type(x) == type(list()):
print "lets see if this works"
if isinstance(x, list): ## most preferred way to check if it's list
print "This should work just fine"
回答by Prometheus
This seems to work for me:
这似乎对我有用:
>>>a = ['x', 'y', 'z']
>>>type(a)
<class 'list'>
>>>isinstance(a, list)
True

