我有以下列表项:
[{"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 = 3
类别1:AAA,类别2:BBB,类别3:CCC-> ResultantName = 4
类别1:XXX,类别2:无,类别3:无-> ResultantName = one
类别1:AAA,类别2:XXX,类别3:无-> ResultantName =两个
类别1:AAA,类别2:BBB,类别3:XXX-> ResultantName = 3
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 - 根据多种条件过滤列表项,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57220585/