파이썬 변수가 문자열인지 목록인지 어떻게 알 수 있습니까?
문자열 목록을 매개 변수로 사용하는 루틴이 있지만 단일 문자열을 전달하고 하나의 문자열 목록으로 변환하는 것을 지원하고 싶습니다. 예를 들면 :
def func( files ):
for f in files:
doSomethingWithFile( f )
func( ['file1','file2','file3'] )
func( 'file1' ) # should be treated like ['file1']
내 함수는 문자열이나 목록이 전달되었는지 어떻게 알 수 있습니까? type
함수 가 있다는 것을 알고 있지만 "더 비단뱀적인"방법이 있습니까?
글쎄, 유형을 확인하는 데 비정상적인 것은 없습니다. 발신자에게 약간의 부담을 주려는 경우 :
def func( *files ):
for f in files:
doSomethingWithFile( f )
func( *['file1','file2','file3'] ) #Is treated like func('file1','file2','file3')
func( 'file1' )
나는 이것이 "명시적인 것이 암묵적인 것보다 낫다"는 점에서 더 비단뱀 적이라고 주장하고 싶다. 입력이 이미 목록 형식 일 때 호출자 측에서 최소한 인식이 있습니다.
isinstance(your_var, basestring)
개인적으로 저는 이런 종류의 행동이별로 마음에 들지 않습니다. 덕 타이핑을 방해합니다. "명시적인 것이 암묵적인 것보다 낫다"라는 진언을 따르지 않는다고 주장 할 수 있습니다. varargs 구문을 사용하지 않는 이유 :
def func( *files ):
for f in files:
doSomethingWithFile( f )
func( 'file1', 'file2', 'file3' )
func( 'file1' )
func( *listOfFiles )
가장 파이썬적인 방법은 목록에 항목이 하나만 있어도 사용자가 항상 목록을 전달하도록하는 것입니다. func()
파일 목록을 가져올 수 있다는 것이 정말 분명해집니다.
def func(files):
for cur_file in files:
blah(cur_file)
func(['file1'])
Dave가 제안한대로 func(*files)
구문을 사용할 수는 있지만이 기능이 마음에 들지 않았습니다. 단순히 목록을 요구하는 것이 더 명시적인 것 같습니다 ( "명시적인 것이 암시적인 것보다 낫다"). 또한 특수한 경우 ( func
단일 파일로 호출 )를 기본 사례로 바꾸는 것입니다. 이제 func
목록 으로 호출하려면 추가 구문을 사용해야하기 때문입니다 .
당신이 문자열 인 인수를위한 특수 케이스를 만들고 싶어 않을 경우, 사용 isinstance()
내장을 하고, 비교 basestring
(이 둘 str()
과 unicode()
에서 파생 된) 예를 들면 :
def func(files):
if isinstance(files, basestring):
doSomethingWithASingleFile(files)
else:
for f in files:
doSomethingWithFile(f)
정말, 나는 단지 하나의 파일로도 목록을 요구하는 것을 제안합니다 (결국 두 개의 추가 문자 만 필요합니다!)
def func(files):
for f in files if not isinstance(files, basestring) else [files]:
doSomethingWithFile(f)
func(['file1', 'file2', 'file3'])
func('file1')
if hasattr(f, 'lower'): print "I'm string like"
발신자를 더 잘 제어 할 수있는 경우 다른 답변 중 하나가 더 좋습니다. 제 경우에는 그런 사치가 없기 때문에 다음 해결책을 결정했습니다 (주의 사항 포함).
def islistlike(v):
"""Return True if v is a non-string sequence and is iterable. Note that
not all objects with getitem() have the iterable attribute"""
if hasattr(v, '__iter__') and not isinstance(v, basestring):
return True
else:
#This will happen for most atomic types like numbers and strings
return False
이 접근 방식은 위의 기준을 충족하는 알려진 유형의 목록 유형을 다루는 경우에 효과적입니다. 하지만 일부 시퀀스 유형은 누락됩니다.
Varargs는 저에게 혼란 스러웠 기 때문에 Python에서 테스트하여 직접 해결했습니다.
먼저 varargs에 대한 PEP가 여기에 있습니다 .
Here is sample program, based on the two answers from Dave and David Berger, followed by the output, just for clarification.
def func( *files ):
print files
for f in files:
print( f )
if __name__ == '__main__':
func( *['file1','file2','file3'] ) #Is treated like func('file1','file2','file3')
func( 'onestring' )
func( 'thing1','thing2','thing3' )
func( ['stuff1','stuff2','stuff3'] )
And the resulting output;
('file1', 'file2', 'file3')
file1
file2
file3
('onestring',)
onestring
('thing1', 'thing2', 'thing3')
thing1
thing2
thing3
(['stuff1', 'stuff2', 'stuff3'],)
['stuff1', 'stuff2', 'stuff3']
Hope this is helpful to somebody else.
참고URL : https://stackoverflow.com/questions/836387/how-can-i-tell-if-a-python-variable-is-a-string-or-a-list
'IT Share you' 카테고리의 다른 글
.NET에서 다음 TCP 포트 찾기 (0) | 2020.11.29 |
---|---|
ASCII 값 목록을 파이썬에서 문자열로 어떻게 변환합니까? (0) | 2020.11.29 |
PHP 배열에 함수를 저장할 수 있습니까? (0) | 2020.11.29 |
'또는'조건이있는 MongoDB 쿼리 (0) | 2020.11.29 |
PHP를 사용하여 이전 URL을 얻는 방법 (0) | 2020.11.29 |