目錄
- 字典串列過濾器
- 需求
- 示例
- 代碼
字典串列過濾器
需求
需求中對 獲取到的字典串列根據關鍵字進行過濾, 篩選符合條件的資料
-
支持單個欄位, 單個或多個資料過濾
{ "name": [ "m1.large","m1.xlarge","wangjw"] } # 過濾欄位 "name", 滿足串列中的任意一個即可 -
支持多個欄位
{ "name":[ "m1.large","m1.xlarge","wangjw"], "ram": 4096 } # 必須同時滿足 name, ram欄位 對應的value值
示例
-
原始資料
d = [ { 'disk': 1, 'id': '1', 'is_disabled': False, 'is_public': True, 'name': 'm1.tiny', 'ram': 512, 'vcpus': 1 }, { 'disk': 20, 'id': '2', 'is_disabled': False, 'is_public': True, 'name': 'm1.small', 'ram': 2048, 'vcpus': 1 }, { 'disk': 40, 'id': '3', 'is_disabled': False, 'is_public': True, 'name': 'm1.medium', 'ram': 4096, 'vcpus': 2 }, { 'disk': 80, 'id': '4', 'is_disabled': False, 'is_public': True, 'name': 'm1.large', 'ram': 8192, 'vcpus': 4 }, { 'disk': 160, 'id': '5', 'is_disabled': False, 'is_public': True, 'name': 'm1.xlarge', 'ram': 16384, 'vcpus': 8 }, { 'disk': 50, 'id': 'abb677c9-1bf2-415d-97bd-ef62574690ed', 'is_disabled': False, 'is_public': True, 'name': 'wangjw', 'ram': 4096, 'vcpus': 2 }, ... ] -
過濾條件如下
filters = { "name": ["m1.large", "m1.xlarge", "wangjw"], "ram": 4096 } -
最終結果
[ { 'disk': 50, 'id': 'abb677c9-1bf2-415d-97bd-ef62574690ed', 'is_disabled': False, 'is_public': True, 'name': 'wangjw', 'ram': 4096, 'vcpus': 2 } ]
代碼
-
代碼如下
#!/usr/bin/env python # ~*~ coding: utf-8 ~*~ def list_filter(l, filters=None): """通過特殊欄位過濾原始串列字典 :param filters: 字典構建的過濾欄位 格式如下 1.同一欄位,匹配多個選項 { "name":[ "m1.large","m1.xlarge","wangjw"] } 2.混合模式多個欄位,不同欄位有獨立的匹配項 { "name":[ "m1.large","m1.xlarge","wangjw"], "ram": 4096 } :param l: 目標字典串列 :return: 過濾后的串列 """ rest_l = copy.deepcopy(l) if not filters: return l for i in rest_l: for k, v in filters.items(): if isinstance(v, (list, tuple)) and i.get(k) not in v: l.remove(i) break elif not isinstance(v, (list, tuple)) and i.get(k) != v: l.remove(i) break return l- 使用copy 是因為字串列字典中 每個元素都是字典, 而字典屬于參考性型別, 整個串列也就變成了參考性型別, 當進行remove操作時, 原始的串列也會更改
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/147674.html
標籤:Python
上一篇:python欄位串列清洗工具
