programing tip

파이썬에서 type == list 여부 확인

itbloger 2020. 8. 5. 07:56
반응형

파이썬에서 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 문이 트리거되지 않습니다. 여기서 내 오류를 발견 할 수 있습니까?


문제는 list코드에서 이전에 변수로 재정의 한 것입니다. 이것은 type(tmpDict[key])==listif가 False같지 않기 때문에 반환 할 때 의미합니다 .

즉, isinstance(tmpDict[key], list)무언가의 유형을 테스트 할 때 대신 사용해야 합니다. 이것은 덮어 쓰는 문제를 피할 수는 list없지만 유형을 확인하는 더 파이썬적인 방법입니다.


당신은 사용해보십시오 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"

이것은 나를 위해 작동하는 것 같습니다 :

>>>a = ['x', 'y', 'z']
>>>type(a)
<class 'list'>
>>>isinstance(a, list)
True

참고 URL : https://stackoverflow.com/questions/26544091/checking-if-type-list-in-python

반응형