itsource

목록의 모든 요소가 동일한 유형인지 확인

mycopycode 2023. 5. 7. 11:24
반응형

목록의 모든 요소가 동일한 유형인지 확인

가능한 경우 모든 요소를 개별적으로 확인하지 않고 목록의 요소가 동일한 유형인지 확인하려면 어떻게 해야 합니까?

예를 들어, 이 목록의 모든 요소가 정수(분명히 거짓임)인지 확인하는 기능을 가지고 싶습니다.

x = [1, 2.5, 'a']

def checkIntegers(x):
    # return True if all elements are integers, False otherwise

다음과 함께 사용해 보십시오.

all(isinstance(x, int) for x in lst)

를 사용하여 여러 유형을 확인할 수도 있습니다.isinstance만약 그것이 원한다면:

all(isinstance(x, (int, long)) for x in lst)

상속된 클래스도 선택하지 않습니다. 예:

class MyInt(int):
     pass

print(isinstance(MyInt('3'),int)) #True

정수로 제한해야 하는 경우 다음을 사용할 수 있습니다.all(type(x) is int for x in lst)하지만 그것은 매우 드문 시나리오입니다.


이 기능을 사용하여 작성할 수 있는 재미있는 기능은 다른 모든 요소가 동일한 유형일 경우 순서대로 첫 번째 요소의 유형을 반환하는 기능입니다.

def homogeneous_type(seq):
    iseq = iter(seq)
    first_type = type(next(iseq))
    return first_type if all( (type(x) is first_type) for x in iseq ) else False

이것은 임의의 임의적인 경우에도 작동하지만 프로세스에서 "반복기"를 사용합니다.

공통 기저 집합을 반환하는 동일한 맥락의 또 다른 재미있는 함수:

import inspect
def common_bases(seq):
    iseq = iter(seq)
    bases = set(inspect.getmro(type(next(iseq))))
    for item in iseq:
        bases = bases.intersection(inspect.getmro(type(item)))
        if not bases:
           break
    return bases

를 사용하면 전체 목록을 통과할 필요가 없습니다.그렇지 않은 물체는 바로 부러집니다.int또는long검색됨:

>>> not any(not isinstance(y,(int,long)) for y in [1,2,3])
True
>>> not any(not isinstance(y,(int,long)) for y in [1,'a',2,3])
False

이미 제공된 답변 중 일부를 map(), type() 및 set()의 조합을 사용하여 imho 다소 읽을 수 있는 답변을 제공합니다.유형 다형성을 확인하지 않는 한계가 있다고 가정하면 됩니다.또한 가장 계산적으로 효율적인 답변은 아니지만 모든 요소가 동일한 유형인지 쉽게 확인할 수 있습니다.

# To check whether all elements in a list are integers
set(map(type, [1,2,3])) == {int}
# To check whether all elements are of the same type
len(set(map(type, [1,2,3]))) == 1

목록이 균일한 요소로 구성되어 있는지 확인하는 가장 간단한 방법은 iter tools 모듈의 기능별 그룹을 사용하는 것입니다.

from itertools import groupby
len(list(groupby(yourlist,lambda i:type(i)))) == 1

then이 하나와 다를 경우 목록에서 다른 종류의 유형을 발견했음을 의미합니다.이는 전체 시퀀스를 통해 실행되는 문제가 있습니다.게으른 버전을 원한다면 다음과 같은 기능을 작성할 수 있습니다.

def same(iterable):
    iterable = iter(iterable)
    try:
        first = type(next(iterable))
        return all(isinstance(i,first) for i in iterable)
    except StopIteration:
        return True

이 함수는 첫 번째 요소의 유형을 저장하고 목록의 요소 중 하나에서 다른 유형을 찾는 즉시 중지합니다.

이 두 가지 방법 모두 유형에 매우 민감하므로 int와 float는 서로 다른 것으로 볼 수 있지만 요청에 최대한 근접해야 합니다.

편집:

mgilson이 제안한 대로 for 사이클을 모두에게 호출로 대체합니다.

void 반복기의 경우 모든 함수에서 Bulit의 동작과 일치하도록 True를 반환합니다.

>>> def checkInt(l):
    return all(isinstance(i, (int, long)) for i in l)

>>> checkInt([1,2,3])
True
>>> checkInt(['a',1,2,3])
False
>>> checkInt([1,2,3,238762384762364892364])
True

나는 엔리코 지암피에리()의 기능을 좋아하지만, 다음을 사용하는 더 간단한 버전이 있습니다.all_equal의 "Itertools 레시피" 섹션에서.itertools문서:문서:

from itertools import groupby

def all_equal(iterable):
    "Returns True if all the elements are equal to each other"
    g = groupby(iterable)
    return next(g, True) and not next(g, False)

이 모든 조리법은 다음과 같이 포장되어 있습니다.more_itertools:

실질적으로 이러한 모든 레시피와 Python Package Index에서 볼 수 있는 더 많은 도구 프로젝트에서 설치할 수 있습니다.

pip install more-itertools

확장된 도구는 기본 도구 세트와 동일한 고성능을 제공합니다.우수한 메모리 성능은 한 번에 하나의 요소를 처리함으로써 유지되며 전체 반복 가능한 메모리를 한꺼번에 메모리로 가져오는 것이 아닙니다.임시 변수를 제거하는 데 도움이 되는 기능적 스타일로 도구를 연결하여 코드 볼륨을 작게 유지합니다.인터프리터 오버헤드가 발생하는 루프용 및 제너레이터보다 "벡터화된" 빌딩 블록을 선호하여 고속을 유지합니다.

from more_itertools import all_equal

all_equal(map(type, iterable))

또는 와 함께isinstance 유형의 리고알려유형진그유.int (원래질문따름에따)름)▁()

all_equal(map(lambda x: isinstance(x, int), iterable))

두 보다 더 하고 ' 반복자 이두가지방를보예엔제의코리안다더보다반처니리합기복고간결하드은이법예를'ators▁these▁'▁(oid▁are:v처(리보▁ways합)를 처리)를 처리합니다.range(0)엔리코의 기능이 하는 것처럼.

all_equal(map(type, range(0))) # True
all_equal(map(type, range(1))) # True
all_equal(map(type, range(2))) # True

all_equal(map(lambda x: isinstance(x, int), range(0))) # True
all_equal(map(lambda x: isinstance(x, int), range(1))) # True
all_equal(map(lambda x: isinstance(x, int), range(2))) # True

사용할 수도 있습니다.type()하위 클래스를 제외하려는 경우.와의 차이점을 참조하십시오.

>>> not any(not type(y) is int for y in [1, 2, 3])
True
>>> not any(not type(y) == int for y in [1, 'a', 2.3])
False

당신이 원하지 않을 수도 있지만, 왜냐하면 이것은 더 취약할 것이기 때문입니다.만약 i가 그것의 종류를 int의 하위 클래스로 바꾼다면, 이 코드는 깨질 것이다, 반면에.isinstance()계속 작동할 것입니다.

사용해도 됩니다.is왜냐하면 오직 하나이기 때문입니다.<type 'int'>메모리에 있으므로 동일한 유형일 경우 동일한 ID를 반환해야 합니다.

목록의 각 항목을 반복하여 모두 동일한 데이터 유형인지 확인하고, Yes(예)인 경우 True(참), False(거짓)을 선호합니다.

def checkIntegers(x):
    # return True if all elements are integers, False otherwise
    return all(isinstance(i, type(x[0])) for i in x[1:])

x = [1, 2.5, 'a']
checkIntegers(x)

False

여기 이와 관련된 간결한 기능이 있으며, 현재 확인합니다(아래 참조).list) 모든 항목이 정수이거나 모든 항목문자열이거나 혼합된 데이터 유형인 경우.

def check_item_dtype_in_list(item_range):
    if all(map(lambda x: str(x).isdigit(), item_range)):
        item_range = list(map(int, item_range))
        print('all are integer')
        print(item_range)
        return 
    elif all(isinstance(item, str) for item in item_range):
        print('all are string')
        print(item_range)
        return 
    elif any(map(lambda x: str(x), item_range)):
        print('mixed dtype')
        print(item_range)
        return 
check_item_dtype_in_list(['2', 2, 3])
check_item_dtype_in_list(["2", 2, 'Two'])
check_item_dtype_in_list(['Two', 'Two', 'Two'])
check_item_dtype_in_list([2, 2., 'Two'])
all are integer
[2, 2, 3]
mixed dtype
['2', 2, 'Two']
all are string
['Two', 'Two', 'Two']
mixed dtype
[2, 2.0, 'Two']
    def c(x):
         for i in x:
             if isinstance(i,str):
                   return False
             if isinstance(i,float):
                   return False

          return True

저는 다음과 같은 경우에 지도를 사용하는 것을 선호합니다.

from types import IntType
In [21]: map((lambda x: isinstance(x, IntType)), x)
   Out[21]: [True, False, False]

언급URL : https://stackoverflow.com/questions/13252333/check-if-all-elements-of-a-list-are-of-the-same-type

반응형