Python筛选列表中符合条件的字典及二次筛选最优实现问询
Pythonic方式筛选字典列表
首先修正你的原始数据变量名(list是Python内置类型,不建议用作变量名):
tools = [ {"hammer": "woodwork", "name": "Mjolnir", "country": "NO"}, {"chisel": "woodwork", "name": "Cold Chisel", "country": "AU"}, {"chisel": "masonry", "name": "Bolster", "country": "AU"}, {"drill": "masonry/woodwork", "name": "All purpose Drill", "country": "NO"} ]
1. 筛选country为"NO"的字典
最Pythonic的写法是列表推导式,语法简洁且执行效率优于手动循环+append:
no_tools = [tool for tool in tools if tool["country"] == "NO"]
这个表达式会遍历tools中的每个字典,仅保留country值为"NO"的条目。
2. 在NO子集基础上筛选包含"woodwork"的字典
有两种实现方式,按需选择:
分步筛选
先获取NO的工具子集,再从中筛选值包含"woodwork"的条目:
no_tools = [tool for tool in tools if tool["country"] == "NO"] no_woodwork_tools = [tool for tool in no_tools if "woodwork" in tool.values()]
一步到位筛选
直接在一次列表推导中加入两个判断条件,代码更紧凑:
no_woodwork_tools = [ tool for tool in tools if tool["country"] == "NO" and "woodwork" in tool.values() ]
这里"woodwork" in tool.values()会检查字典的所有值是否包含"woodwork"子串,能匹配你例子中"woodwork"和"masonry/woodwork"两种情况。
内容的提问来源于stack exchange,提问作者Marcus Webb
相关产品推荐
相关产品推荐

