【问题标题】:python lambda expression with dynamic fields具有动态字段的python lambda表达式
【发布时间】:2018-08-24 14:14:52
【问题描述】:

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

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 中的项目并在每次迭代中按一个字段过滤。有什么巧妙的方法吗?

【问题讨论】:

    标签: python lambda filter


    【解决方案1】:

    您需要一个 all 函数,该函数仅在可迭代对象的每个元素都为 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)]
    

    【讨论】:

      猜你喜欢
      • 2018-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多