我的列表项如下:
[{"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: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
但这不适用于我的所有情况。
请对此提供帮助。
答案 0 :(得分:1)
您可以构建一个字典,其中每个条目都是一个条件:键将是一个具有类别值(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'的值替换为None
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'