특정 값과 동일한 속성을 가진(모든 조건을 충족하는) 목록에서 개체 찾기
물건 목록이 있어요이 목록에서 다음과 같은 속성(또는 메서드 결과 - 임의)을 가진 개체를 하나 찾습니다.value
.
어떻게 하면 찾을 수 있을까요?
테스트 케이스는 다음과 같습니다.
class Test:
def __init__(self, value):
self.value = value
import random
value = 5
test_list = [Test(random.randint(0,100)) for x in range(1000)]
# that I would do in Pascal, I don't believe it's anywhere near 'Pythonic'
for x in test_list:
if x.value == value:
print "i found it!"
break
발전기를 사용해서reduce()
아직 목록을 통해 반복되기 때문에 차이가 없습니다.
ps.: 방정식 대value
예에 불과합니다.물론 어떤 조건에도 부합하는 요소를 원합니다.
next((x for x in test_list if x.value == value), None)
그러면 조건과 일치하는 목록의 첫 번째 항목이 가져오고 반환됩니다.None
일치하는 항목이 없는 경우.제가 선호하는 단일 표현 형식입니다.
하지만,
for x in test_list:
if x.value == value:
print("i found it!")
break
순진한 루프 브레이크 버전은 완벽하게 피토닉식입니다.간결하고 명확하며 효율적입니다원라이너의 동작과 일치시키려면:
for x in test_list:
if x.value == value:
print("i found it!")
break
else:
x = None
이렇게 하면 할당됩니다.None
로.x
하지 않으면break
고리를 벗어나다.
완성을 위해서만 언급되지 않았기 때문에.필터링 대상 요소를 필터링하기 위한 양호한 ol' 필터.
기능 프로그래밍 ftw.
####### Set Up #######
class X:
def __init__(self, val):
self.val = val
elem = 5
my_unfiltered_list = [X(1), X(2), X(3), X(4), X(5), X(5), X(6)]
####### Set Up #######
### Filter one liner ### filter(lambda x: condition(x), some_list)
my_filter_iter = filter(lambda x: x.val == elem, my_unfiltered_list)
### Returns a flippin' iterator at least in Python 3.5 and that's what I'm on
print(next(my_filter_iter).val)
print(next(my_filter_iter).val)
print(next(my_filter_iter).val)
### [1, 2, 3, 4, 5, 5, 6] Will Return: ###
# 5
# 5
# Traceback (most recent call last):
# File "C:\Users\mousavin\workspace\Scripts\test.py", line 22, in <module>
# print(next(my_filter_iter).value)
# StopIteration
# You can do that None stuff or whatever at this point, if you don't like exceptions.
일반적으로 python 목록에서는 comprehensions가 선호되거나 적어도 제가 읽은 내용이라는 것을 알고 있지만, 솔직히 이 문제는 알 수 없습니다.물론 Python은 FP 언어는 아니지만, Map / Reduce / Filter는 완벽하게 읽을 수 있으며 기능 프로그래밍에서 가장 표준적인 사용 사례입니다.
자, 여기 있습니다.기능 프로그래밍을 이해합니다.
필터 조건 리스트
이보다 더 쉬워지진 않을 겁니다.
next(filter(lambda x: x.val == value, my_unfiltered_list)) # Optionally: next(..., None) or some other default value to prevent Exceptions
간단한 예:다음과 같은 어레이가 있습니다.
li = [{"id":1,"name":"ronaldo"},{"id":2,"name":"messi"}]
이제 id가 1인 어레이 내의 개체를 찾습니다.
- 사용방법
next
일람표를 이해하여
next(x for x in li if x["id"] == 1 )
- 목록 이해 사용 및 첫 번째 항목 반환
[x for x in li if x["id"] == 1 ][0]
- 커스텀 기능
def find(arr , id):
for x in arr:
if x["id"] == id:
return x
find(li , 1)
위의 모든 메서드를 출력합니다.{'id': 1, 'name': 'ronaldo'}
이런 것도 할 수 있고
dict = [{
"id": 1,
"name": "Doom Hammer"
},
{
"id": 2,
"name": "Rings ov Saturn"
}
]
for x in dict:
if x["id"] == 2:
print(x["name"])
그것이 내가 긴 배열의 객체에서 객체를 찾을 때 사용하는 것이다.
오래된 질문입니다만, 저는 이것을 꽤 자주 사용하고 있습니다(버전 3.8의 경우).이것은 약간 구문적인 소금이지만, 상위 답변보다 더 좋은 점은 단순히 제거함으로써 결과 목록을 가져올 수 있다는 것입니다(복수인 경우).[0]
디폴트로는None
아무것도 발견되지 않으면.다른 조건의 경우, 단순히 변경만 하면 됩니다.x.value==value
을 사용법
_[0] if (_:=[x for x in test_list if x.value==value]) else None
또, 고객의 요구에 대해서, 풍부한 비교 방법을 사용해 실장할 수도 있습니다.Test
및 를합니다.in
이 방법인지는 , 만약 가 필요할 경우.Test
「」에 value
다른 곳에서 유용하게 쓸 수 있을 거야
class Test:
def __init__(self, value):
self.value = value
def __eq__(self, other):
"""To implement 'in' operator"""
# Comparing with int (assuming "value" is int)
if isinstance(other, int):
return self.value == other
# Comparing with another Test object
elif isinstance(other, Test):
return self.value == other.value
import random
value = 5
test_list = [Test(random.randint(0,100)) for x in range(1000)]
if value in test_list:
print "i found it"
저는 방금 비슷한 문제에 부딪혔고, 목록에 요건을 충족하는 개체가 없는 경우를 위한 작은 최적화를 고안했습니다(사용 사례의 경우 성능이 크게 향상되었습니다).
test_list 목록과 함께 필터링해야 하는 목록 값으로 구성된 추가 set test_value_set을 보유하고 있습니다.따라서 agf 솔루션의 다른 부분은 매우 빨라집니다.
아래 코드의 경우 xGen은 비노노믹 제너레이터 식이고 yFilt는 필터 객체입니다.xGen의 경우 목록이 모두 사용되었을 때 StopIteration을 던지는 대신 추가 None 매개 변수가 반환된다는 점에 유의하십시오.
arr =((10,0), (11,1), (12,2), (13,2), (14,3))
value = 2
xGen = (x for x in arr if x[1] == value)
yFilt = filter(lambda x: x[1] == value, arr)
print(type(xGen))
print(type(yFilt))
for i in range(1,4):
print('xGen: pass=',i,' result=',next(xGen,None))
print('yFilt: pass=',i,' result=',next(yFilt))
출력:
<class 'generator'>
<class 'filter'>
xGen: pass= 1 result= (12, 2)
yFilt: pass= 1 result= (12, 2)
xGen: pass= 2 result= (13, 2)
yFilt: pass= 2 result= (13, 2)
xGen: pass= 3 result= None
Traceback (most recent call last):
File "test.py", line 12, in <module>
print('yFilt: pass=',i,' result=',next(yFilt))
StopIteration
Python 배열에서 개체를 찾고 있는 경우.조건부로 사용할 수 있습니다.
model_t1 = [0,1,2,3,4]
model_t2 = [7,8,9,15,14]
_data = model_t1
for md in model_t2:
_data.append(md)
for p_data in _data:
if len(p_data['Property']) == 'Value':
print(json(p_data))
언급URL : https://stackoverflow.com/questions/7125467/find-object-in-list-that-has-attribute-equal-to-some-value-that-meets-any-condi
'programing' 카테고리의 다른 글
node.js에서 한 줄씩 파일을 읽으시겠습니까? (0) | 2022.12.21 |
---|---|
Http Security, Web Security 및 Authentication Manager Builder (0) | 2022.12.21 |
Vue Router & Vuex : 페이지 새로 고침 시 Getter가 정의되지 않음 (0) | 2022.12.21 |
MySQL에서 DateTime 필드의 시간 부분을 무시하는 날짜 비교 (0) | 2022.12.21 |
프로그램 종료 전에 malloc 후에 자유롭지 않으면 실제로 어떤 일이 일어날까요? (0) | 2022.12.21 |