1

オブジェクトの配列があり (それらはすべて同じオブジェクト タイプです)、それらには複数の属性があります。すべての属性がテスト ケース、文字列、その属性タイプが何であれ、一致するオブジェクトのより小さな配列を返す方法はありますか。

4

1 に答える 1

5

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))
于 2013-04-24T07:51:20.530 に答える