2017-02-21 84 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。