检查python中的type == list [英] Checking if type == list in python
问题描述
我可能在这里放屁了,但我真的不知道我的代码有什么问题:
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
输出是
但 if 语句永远不会触发.有人能在这里发现我的错误吗?
the output is <type 'list'>
but the if statement never triggers. Can anyone spot my error here?
推荐答案
您的问题是您之前在代码中将 list
重新定义为变量.这意味着当你执行 type(tmpDict[key])==list
if 会返回 False
因为它们不相等.
Your issue is that you have re-defined list
as a variable previously in your code. This means that when you do type(tmpDict[key])==list
if will return False
because they aren't equal.
话虽如此,您应该改用 isinstance(tmpDict[key], list)
测试某事物的类型时,这不会避免覆盖 list
的问题,而是一种更 Pythonic 的检查类型的方式.
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 list
but is a more Pythonic way of checking the type.
这篇关于检查python中的type == list的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!