[英]Check for multiple attribute matches in an array of objects
我有一个对象数组(它们都是相同的对象类型),并且它们具有多个属性,有没有一种方法可以返回较小的对象数组,其中所有属性都与测试用例,字符串匹配,无论该属性类型是什么。
Use a list comprehension with all()
; 对all()
使用列表理解; the following presumes that a list_of_attributes
has been predefined to enumerate what attributes you wanted to test: 以下假定已经预定义了list_of_attributes
来枚举您要测试的属性:
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 : 或者您可以使用filter()
函数 :
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 ; 您可以使用vars()
函数测试所有属性,而不是使用预定义的list_of_attributes
; this presumes that all instance attributes need to be tested: 假设所有实例属性都需要测试:
all(value == 'some test string' for key, value in vars(ob))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.