developer tip

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

optionbox 2020. 9. 25. 07:48
반응형

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


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

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

매번 전체 목록을 살펴보고 싶지는 않습니다. 일치하는 인스턴스가 1 개 있는지 확인하면됩니다. first(...)또는 any(...)또는 뭔가 다른 그런 짓을?


쉽게에서 볼 수 있듯이 문서any()기능 단락은 반환 True곧 경기로 발견되었습니다.

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

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

반응형