results = [
{'id': 1, 'text': 'String 55 - 1' },
{'id': 2, 'text': 'String 3 - 2' },
{'id': 3, 'text': 'String 5 - 4 - 1'}]
str = [' 5 ', ' 4 ']
我想从 results 中删除所有不包含 text 中 str 列表中每个字符串的字典。目前我可以在一个条件下完成,例如:
results[:] = [d for d in results if lst[0] in d['text']]
但这不会检查 ' 4 ' 是否也在文本中。
请您参考如下方法:
只需使用 all测试列表中的所有项是否在字典值中并在列表理解的过滤器中使用它:
lst = [' 5 ', ' 4 ']
results[:] = [d for d in results if all(i in d['text'] for i in lst)]
print(results)
# [{'text': 'String 5 - 4 - 1', 'id': 3}]
