繁体   English   中英

Python-如果字符串列表不在字典键中,则从字典列表中删除字典

[英]Python - Remove dictionary from list of dictionaries if list of strings not in dictionary key

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}]

您可以在理解的情况下使用all

results = [
        {'id': 1, 'text': 'String 55 - 1' },
        {'id': 2, 'text': 'String 3 - 2' },
        {'id': 3,  'text': 'String 5 - 4 - 1'}]

strs = [' 5 ', ' 4 ']  # you shouldn't name it "str" because that's a builtin function

>>> [dct for dct in results if all(substr in dct['text'] for substr in strs)]
[{'id': 3, 'text': 'String 5 - 4 - 1'}]

您还可以使用set.issubsetstr.split代替:

strs = {'5', '4'}  # this is a set!

[dct for dct in results if strs.issubset(dct['text'].split())]

这将检查在空格处分割的['text']包含strs中的所有字符。 根据长度text和项目的数量strs ,这可能是比快all -approach。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM