-3

我需要使用自定义逻辑执行过滤器。我定义了一个函数如下:

def isValid(str):
 if str=='test':
  true
 else:
  false

并从过滤器 lambda 调用它,如下所示:

data.filter(lambda obj: isValid(obj['str'])

这行不通。我错过了什么?

4

1 回答 1

0

如果您的要求如下所示:

data = [
    {'name': "group1", "str":"test"}, 
    {'name': "group2", "str":"validation"}, 
    {'name': "group2", "str":"test"}
]

def isValid(str):
    if str=='test':
        return True
    else:
        return False

filtered_list = list(filter(lambda obj: isValid(obj['str']), data))
print(filtered_list)


output : [{'name': 'group1', 'str': 'test'}, {'name': 'group2', 'str': 'test'}]
###Note: object having test as value of key str is filtered
于 2020-06-26T18:26:55.530 回答