簡體   English   中英

檢查對象數組中是否有多個屬性匹配

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM