programing

개체 목록에 특정 속성 값을 가진 개체가 포함되어 있는지 확인합니다.

codeshow 2023. 4. 12. 22:41
반응형

개체 목록에 특정 속성 값을 가진 개체가 포함되어 있는지 확인합니다.

개체 목록에 특정 속성 값을 가진 개체가 포함되어 있는지 확인합니다.

class Test:
    def __init__(self, name):
        self.name = name

# in main()
l = []
l.append(Test("t1"))
l.append(Test("t2"))
l.append(Test("t2"))

목록에 이름이 있는 개체가 포함되어 있는지 확인하는 방법을 원합니다."t1"예를들면.어떻게 할 수 있을까요?https://stackoverflow.com/a/598415/292291,을 찾았습니다.

[x for x in myList if x.n == 30]               # list of all matches
any(x.n == 30 for x in myList)                 # if there is any matches
[i for i,x in enumerate(myList) if x.n == 30]  # indices of all matches

def first(iterable, default=None):
    for item in iterable:
        return item
    return default

first(x for x in myList if x.n == 30)          # the first match, if any

매번 모든 목록을 검토하고 싶지는 않습니다. 일치하는 인스턴스가 하나만 있으면 됩니다.할 것이다first(...)또는any(...)아니면 다른 뭔가가 그렇게 하나요?

매뉴얼에서 쉽게 알 수 있듯이any()함수를 통해 수익을 단축하다True일치하는 것이 발견되면 바로 찾아냅니다.

any(x.name == "t2" for x in l)

또 다른 내장 기능next()이 작업에 사용할 수 있습니다.이 상태는 첫 번째 인스턴스에서 정지됩니다.True꼭 닮다any().

next((True for x in l if x.name=='t2'), False)

또한.next()조건이 있는 오브젝트 자체를 반환할 수 있습니다.True(그렇게 동작합니다)first()기능을 합니다).

next((x for x in l if x.name == 't2'), None)

언급URL : https://stackoverflow.com/questions/9371114/check-if-list-of-objects-contain-an-object-with-a-certain-attribute-value

반응형