python - 用字典搜索列表,条件函数
问题描述
我有一个列表,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()
我不想打印1
and ,而是执行不同的功能,例如.2
print('ABC')
任何关于我如何实现这一目标的方向都将不胜感激。
解决方案
您可以使用帮助程序检查是否满足此条件,然后运行您想要的任何内容。由于只有知道一个类别匹配后才能执行这些功能,因此您需要检查两次类别。
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()
推荐阅读
- python - 基于 Telethon 的侦听器不响应 AWS 上的新消息
- .net - 如何在打开特定文件的 Visual Studio 工具栏上放置一个按钮?
- python - python重新查找模式并拆分为列表
- hl7-fhir - 无法使用 Simplifier.net 验证包含的资源
- python-3.x - 如何在现有数据库上初始化 Alembic
- c++ - 使用 omp 进行并行化和同步
- android - 为什么在 Compose 中使用 jetpack 导航时视图一直闪烁?
- windows - 如何在这个混合的 cmd / powershell 代码中转义毒字符?
- javascript - jquery ajax 发送字符串数据和文件数据 PHP
- javascript - 未定义不和谐音乐机器人“连接”(discord.js)