python - 根据多个条件过滤列表项
问题描述
我有如下列表项:
[{"category1": None, "category2": None, "category3": None, "Name": "one"}, {"category1": "AAA", "category2": None, "category3": None, "Name": "two"} {"category1": "AAA", "category2": "BBB", "category3": None, "Name": "three"}, {"category1": "AAA", "category2": "BBB", "category3": "CCC", "Name": "four"}]
并需要根据以下条件选择项目
- 类别 1:无,类别 2:无,类别 3:无 -> ResultantName=one
- 类别 1:AAA,类别 2:无,类别 3:无 -> ResultantName=two
- 类别 1:AAA,类别 2:BBB,类别 3:无 -> ResultantName=three
- 类别 1:AAA,类别 2:BBB,类别 3:CCC -> ResultantName=4
- 类别 1:XXX,类别 2:无,类别 3:无 -> ResultantName=one
- 类别 1:AAA,类别 2:XXX,类别 3:无 -> ResultantName=2
类别1:AAA,类别2:BBB,类别3:XXX -> ResultantName=three
categories = {'category1':'AAA','category2':'XXX','category3':None}
对于列表中的模板(模板):
if categories.get('category1'):
if template.get('category1') and template.get('category1') !=categories.get('category1'):
templates.remove(template)
continue
elif categories.get('category1') is None:
if template.get('category1') is not None:
templates.remove(template)
continue
if categories.get('category2'):
if template.get('category2') and template.get('category2') !=categories.get('category2'):
templates.remove(template)
continue
elif categories.get('category2') is None:
if template.get('category2') is not None:
templates.remove(template)
continue
if categories.get('category3'):
if template.get('category3') and template.get('category3') !=categories.get('category3'):
templates.remove(template)
continue
elif categories.get('category3') is None:
if template.get('category3') is not None:
templates.remove(template)
continue
但这不适用于我的所有条件。
请帮助解决这个问题。
解决方案
您可以构建一个字典,其中每个条目都是一个条件:键将是一个元组,其中包含类别 ( category1
, category2
, category3
) 的值。然后,输入值将成为您的目标变量 ( Name
),例如:
names['AAA', 'BBB', None] # "three"
names[None, None, None] # "one"
假设有一个变量conditions
是您在第一个代码片段中编写的列表变量,您可以使用以下内容构建字典names
:
from operator import itemgetter
keys = map(itemgetter('category1', 'category2', 'category3'), conditions)
values = map(itemgetter('Name'), conditions)
names = dict(zip(keys, values))
要通过 访问字典get
,您需要明确传递一个包含类别的元组:
names.get(('AAA', 'BBB', None))
编辑:下一个函数get_name(...)
等效于names[...]
但它将类别“XXX”值替换为无
def get_name(*args):
categories = tuple(map(lambda arg: arg if arg != 'XXX' else None, args))
return names.get(categories)
get_name('AAA', 'BBB', 'XXX') # 'two'
get_name('AAA', 'BBB', None) # 'two'
推荐阅读
- python - Jupyter Notebook Azure 机器学习实验
- python - 如何读取 div id
- .net - EPPlus 计算方法在 Matlab 中不可见或无法访问
- elixir - 使用 NaiveDateTime 在 Elixir 中获取 3 天前
- python - Python 中的布尔输入
- powershell - 使用 IP 地址和凭据在远程计算机上调用命令
- javascript - 如何使用 html、javascript 和 css 为条形图中的每个条添加输入文本框
- google-app-engine - AppEngine Python flex env 的最新点子?
- spring - Springboot AutoConfiguratoin 在 Kafka Logback Appender 中不起作用
- python - 在 Python 中实现 WGET 和 GREP 的最佳方法