Pythonでtype == listかどうかを確認する [重複] 質問する

Pythonでtype == listかどうかを確認する [重複] 質問する

コードの何が問題なのかわかりません:

for key in tmpDict:
    print type(tmpDict[key])
    time.sleep(1)
    if(type(tmpDict[key])==list):
        print 'this is never visible'
        break

出力はあります<type 'list'>が、if ステートメントはトリガーされません。誰か私のエラーに気付いてもらえますか?

ベストアンサー1

ぜひ使ってみてくださいisinstance()

if isinstance(object, list):
       ## DO what you want

あなたの場合

if isinstance(tmpDict[key], list):
      ## DO SOMETHING

詳しく説明すると:

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"

と の違いはisinstance()type()どちらも同じ機能を果たすように見えますが、 はisinstance()サブクラスもチェックするのに対し、 はサブクラスをチェックtype()しないという点です。

おすすめ記事