用字典,条件函数搜索列表

时间:2018-08-02 17:07:37

标签: python python-3.x list dictionary search

我有一个列表categories,其中存储了一些不同的值。我使用的是字典my_dict,以查看categories中是否有匹配的特定值。如果存在,将对字典中的每个键执行唯一的功能。

我的代码当前如下所示:

categories = ['Creams', 'Bath', 'Personal Care']

my_dict = {
    'Conditioners': lambda: print(1),
    'Bath': lambda: print(2),
    'Shaving Gels': lambda: print(3)
}


for category in categories:
    fn = my_dict.get(category, lambda: None)
    fn()

哪个输出:

 2

我现在想做的是,无论如何,我在字典中有两个或多个值,它们在categories中,我想做一个唯一的函数,不同于为它们指定的函数

例如:

categories = ['Creams', 'Bath', 'Personal Care']

my_dict = {
    'Creams': lambda: print(1),
    'Bath': lambda: print(2),
    'Shaving Gels': lambda: print(3)
}


for category in categories:
    fn = my_dict.get(category, lambda: None)
    fn()

我不想打印12,而是执行其他功能,例如print('ABC')

任何有关如何实现这一目标的方向都将受到赞赏。

1 个答案:

答案 0 :(得分:0)

您可以使用帮助程序来检查是否满足此条件,然后运行任何您想要的条件。由于只有等到一个类别匹配后才能执行这些功能,因此您需要两次浏览类别。

def two_or_more_categories_in_dict(categories, dict):
    """Returns true if there are more than two categories in the dict"""
    num_cats_in_dict = 0
    for cat in categories:
        if cat in dict:
            num_cats_in_dict += 1
    if num_cats_in_dict > 1:
        return True
    else:
        return False


    categories = ['Creams', 'Bath', 'Shaving Gels']    

    my_dict = {
        'Creams': f1,
        'Bath': f2,
        'Shaving Gels': f3
    }

    if two_or_more_categories_in_dict(categories, dict):
        #<unique lambda for this case>
    else:
        for category in categories:
            fn = my_dict.get(category, lambda: None)
            fn()