[英]Delete elements from dicts in list if value of dict key is in otherlist
我有以下代碼:
dicts = [
{'one': 'hello',
'two': 'world',
'three': ['a', 'b', 'c', 'd'],
'four': 'foo'
},
{'one': 'pizza',
'two': 'cake',
'three': ['f', 'g', 'h', 'e'],
'four': 'bar'
}
]
letters = ['q', 'w', 'e', 'r','t','y']
dedup_rows = [row for row in dicts if row['three'][3] not in letters]
目的是dedup_rows
應包含的元素dicts
,其中存儲在所述列表中的所述第四元件three
不包含在列表中letters
。 基本上, delete row from dicts if row['three'][3] in letters
。 上面代碼的輸出將是:
dedup_rows: [
{'one': 'hello',
'two': 'world',
'three': ['a', 'b', 'c', 'd'],
'four': 'foo'
}
]
我的代碼是工作,但在實踐中,兩種dicts
和letters
包含數十萬個元素的每所以執行是緩慢的,因為每個迭代超過dicts
也需要在一個完整的迭代letters
。
在Python中有更好的方法嗎?
你的代碼dedup_rows = [row for row in dicts if row['three'][3] not in letters]
是方形復雜度。 因為它是迭代dicts
和letters
的每個元素dicts
。
如果兩個列表都包含大量元素。 您應該考慮具有大約一的查找時間復雜度的數據結構。 對於您的情況, Python集是完美的。 您可以閱讀更多相關信息。
您需要做的就是將letters = ['q', 'w', 'e', 'r','t','y']
轉換為具有語法set(letters)
的集合,並x in letters_set
使用語法x in letters_set
。
dicts = [
{'one': 'hello',
'two': 'world',
'three': ['a', 'b', 'c', 'd'],
'four': 'foo'
},
{'one': 'pizza',
'two': 'cake',
'three': ['f', 'g', 'h', 'e'],
'four': 'bar'
}
]
letters = ['q', 'w', 'e', 'r','t','y']
letters_set = set(letters)
dedup_rows = [row for row in dicts if row['three'][3] not in letters_set]
像這樣你可以將算法從n平方的順序改為n的順序。
如果你真的在處理數十萬條記錄,每行記錄的行數都是數十萬,那么也許純粹的內存python方法並不是最好的方法。
您可以做一些可以提高性能的方法:
但總的來說,這引出了從哪里獲取這些記錄的問題?
如果它們存儲在任何類型的數據庫中,那么在源處執行查詢以排除您不想要的行,並提供游標以內存有效的方式迭代您想要的行聽起來像是一種更好的方法走。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.