반응형
개체 목록에 특정 속성 값을 가진 개체가 포함되어 있는지 확인합니다.
개체 목록에 특정 속성 값을 가진 개체가 포함되어 있는지 확인합니다.
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
반응형
'programing' 카테고리의 다른 글
Bash 스크립트의 클립보드에 연결/연결 (0) | 2023.04.12 |
---|---|
공백으로 구분된 문자열을 Bash에서 배열로 읽기 (0) | 2023.04.12 |
코드를 사용하여 데스크톱의 벽지를 변경합니다.그물 (0) | 2023.04.12 |
정수 배열을 쉼표로 구분된 문자열로 변환 (0) | 2023.04.12 |
Swift 클래스 오류: super.init 호출 시 속성이 초기화되지 않았습니다. (0) | 2023.04.12 |