首页 > 解决方案 > 用字典搜索列表,条件函数

问题描述

我有一个列表,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

我现在想做的是,如果在任何情况下,我在字典中有 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()

我不想打印1and ,而是执行不同的功能,例如.2print('ABC')

任何关于我如何实现这一目标的方向都将不胜感激。

标签: pythonpython-3.xlistdictionarysearch

解决方案


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

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()

推荐阅读