티스토리 뷰

반응형

Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.

Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.

 

아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.

How to check if an object is a list or tuple (but not string)?

객체가 리스트 또는 튜플인지 (하지만 문자열은 아닌지) 확인하는 방법은 무엇인가요?

 문제 내용 

This is what I normally do in order to ascertain that the input is a list/tuple - but not a str. Because many times I stumbled upon bugs where a function passes a str object by mistake, and the target function does for x in lst assuming that lst is actually a list or tuple.

일반적으로 리스트 또는 튜플인지 (하지만 문자열은 아닌지) 확인하려면 다음을 수행합니다. 대부분의 경우, 함수에서 실수로 str 객체를 전달하는 경우 버그가 발생하기 때문에 이 작업을 수행합니다. 그리고 대상 함수는 실제로 리스트 또는 튜플인 줄 알고 lst에 대해 for x in lst를 수행합니다.
assert isinstance(lst, (list, tuple))

 

My question is: is there a better way of achieving this?

내 질문은: 이를 더 잘 달성하는 방법이 있나요?

 

 

 

 높은 점수를 받은 Solution 

In python 2 only (not python 3):

파이썬 2에서만 해당됩니다 (파이썬 3에서는 해당되지 않습니다):
assert not isinstance(lst, basestring)

 

Is actually what you want, otherwise you'll miss out on a lot of things which act like lists, but aren't subclasses of list or tuple.

이것이 실제로 원하는 것이며, 그렇지 않으면 list나 tuple의 서브 클래스가 아닌 것들이 많은 것을 놓치게 될 것입니다.

 

 

 

 가장 최근 달린 Solution 

Try this for readability and best practices:

가독성과 최선의 방법을 위해 다음과 같이 시도해보세요:

 

Python2 - isinstance()

import types
if isinstance(lst, types.ListType) or isinstance(lst, types.TupleType):
    # Do something

 

Python3 - isinstance()

import typing
if isinstance(lst, typing.List) or isinstance(lst, typing.Tuple):
    # Do something

 

Hope it helps.

도움이 되길 바랍니다.

 

 

 

출처 : https://stackoverflow.com/questions/1835018/how-to-check-if-an-object-is-a-list-or-tuple-but-not-string

반응형
댓글
공지사항
최근에 올라온 글