首页 > 解决方案 > 根据多个条件过滤列表项

问题描述

我有如下列表项:

[{"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"}]

并需要根据以下条件选择项目

对于列表中的模板(模板):

    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

但这不适用于我的所有条件。

请帮助解决这个问题。

标签: pythonlist

解决方案


您可以构建一个字典,其中每个条目都是一个条件:键将是一个元组,其中包含类别 ( 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'

推荐阅读