我有一个对象数组(它们都是相同的对象类型),并且它们具有多个属性,有没有一种方法可以返回较小的对象数组,其中所有属性都与测试用例,字符串匹配,无论该属性类型是什么。
Use a list comprehension with all()
; the following presumes that a list_of_attributes
has been predefined to enumerate what attributes you wanted to test:
sublist = [ob for ob in larger_list if all(getattr(ob, attr) == 'some test string' for attr in list_of_attributes)]
Alternatively, if your input list is large, and you only need to access the matching elements one by one, use a generator expression:
filtered = (ob for ob in larger_list if all(getattr(ob, attr) == 'some test string' for attr in list_of_attributes))
for match in filtered:
# do something with match
or you can use the filter()
function :
filtered = filter(lambda ob: all(getattr(ob, attr) == 'some test string' for attr in list_of_attributes)
for match in filtered:
# do something with match
Instead of using a pre-defined list_of_attributes
, you could test all the attributes with the vars()
function ; this presumes that all instance attributes need to be tested:
all(value == 'some test string' for key, value in vars(ob))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.