2017-02-21 86 views
1
results = [ 
     {'id': 1, 'text': 'String 55 - 1' }, 
     {'id': 2, 'text': 'String 3 - 2' }, 
     {'id': 3, 'text': 'String 5 - 4 - 1'}] 

str = [' 5 ', ' 4 '] 

我想从results不包含在str列表中text每一个字符串中的每个字典中删除列表。目前,我可以用一个条件做到这一点,例如:Python的 - 从字典列表中删除词典,如果字符串不是在字典中的关键

results[:] = [d for d in results if lst[0] in d['text']] 

,但这不会检查是否' 4 '在文本了。

+0

它清楚你需要2个循环。 –

+0

我想你命名了你的字符串列表'str',但是在理解中你使用'lst'。你可能会[编辑]你的问题,这是可以验证的吗? :) – MSeifert

回答

3

只需使用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}] 
2

你可以在使用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'}] 

你库仑也D使用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。