python - 检查存储为字典值的列表中是否存在特定文本
问题描述
我将列表存储为字典中的值。我正在尝试查看这些列表中是否存在特定值,但似乎无法弄清楚为什么以下内容不起作用。按原样运行以下代码当前不会打印任何内容。
dictionaryTest = {'First': ['Test1', 'Test2'], 'Second': ['Test3'], 'Third': ['Test4', 'Test5', 'Test6', 'Test7']}
if 'Test6' in [i for i in dictionaryTest.values()]:
print('Found it!')
解决方案
[i for i in dictionaryTest.values()]
等于[['Test1', 'Test2'], ['Test3'], ['Test4', 'Test5', 'Test6', 'Test7']]
但不等于['Test1', 'Test2', 'Test3', 'Test4', 'Test5', 'Test6', 'Test7']
(并且in
运算符不是递归的)。
您想要的是检查是否'Test6'
在任何子项中,即:
if any('Test6' in items for items in dictionaryTest.values()):
print('Found it!')
此解决方案遍历字典值(列表),并且对于每个值,它检查字符串'Test6'
是否在子列表中(使用表达式'Test6' in items
)。如果在任何子列表中找到该字符串,则采用该条件。
推荐阅读
- python - 哪个 python 和 tensorflow 版本用于使用 tensorflow api 训练 DeepLab v3+?
- sql - 我想找到从 2017 年到 2018 年连续 3 个月进行交易的客户
- azure - 从 Blob Storage .net core Azure Function C# 下载文件
- angular - 为什么 Ionic 4 Ion-Slides 突然停止正常显示?
- aws-lambda - 创建 lambda 层的代码构建 - 找不到模块
- r - 引用先前行的 for 循环
- c# - 将 mvc 应用程序部署到 aws 后出现服务器错误
- subdomain - 关于在 cPanel 上创建子域
- java - 如何从另一个线程调用 JAWT_FreeDrawingSurface?
- java - java - 如何判断命令提示符的实例何时关闭,在java中?