具有动态字段的python lambda表达式

时间:2018-08-24 14:14:52

标签: python lambda filter

我有一个字典清单。我希望能够使用字段的动态列表过滤此列表。这样;

my_list = [{'a': 1, 'b': 1, 'c': 1}, {'a': 1, 'b': 1, 'c': 2}, {'a': 1, 'b': 2, 'c': 2}]
reference_row = {'a': 1, 'b': 1, 'c': 1}

compare_fields = ['a'] # Compares only field 'a' of reference row with rows in my_list 
# Magical filter expression results in [{'a': 1, 'b': 1, 'c': 1}, {'a': 1, 'b': 1, 'c': 2}, {'a': 1, 'b': 2, 'c': 2}]

compare_fields = ['a', 'b'] # Compares fields 'a' and 'b' of reference row with rows in my_list 
# Magical filter expression results in [{'a': 1, 'b': 1, 'c': 1}, {'a': 1, 'b': 1, 'c': 2}]

compare_fields = ['a', 'b', 'c'] # Compares fields 'a', 'b' and 'c' of reference row with rows in my_list 
# Magical filter expression results in [{'a': 1, 'b': 1, 'c': 1}]

我已经尝试过类似以下的操作,但是没有用:

list(filter(lambda d: (d[field] == reference_row[field] for field in compare_fields ), my_list))

我不想遍历compare_fields中的项目并在每次迭代中按一个字段进行过滤。有什么巧妙的方法吗?

1 个答案:

答案 0 :(得分:2)

您需要一个all函数,该函数仅在iterable的每个元素均为True时才为true。否则,过滤器的每个输入都会返回True

list(filter(lambda d: all(d[field] == reference_row[field] for field in compare_fields), my_list))

我认为这比较干净

[d for d in my_list if 
 all(d[field] == reference_row[field] for field in compare_fields)]