![](/img/trans.png)
[英]Python: any() to check if attribute in List of Objects matches a list
[英]Check for multiple attribute matches in an array of objects
我有一个对象数组(它们都是相同的对象类型),并且它们具有多个属性,有没有一种方法可以返回较小的对象数组,其中所有属性都与测试用例,字符串匹配,无论该属性类型是什么。
对all()
使用列表理解; 以下假定已经预定义了list_of_attributes
来枚举您要测试的属性:
sublist = [ob for ob in larger_list if all(getattr(ob, attr) == 'some test string' for attr in list_of_attributes)]
或者,如果您的输入列表很大,并且您只需要一个一个地访问匹配的元素,请使用生成器表达式:
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
或者您可以使用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
您可以使用vars()
函数测试所有属性,而不是使用预定义的list_of_attributes
; 假设所有实例属性都需要测试:
all(value == 'some test string' for key, value in vars(ob))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.