python - python:当字典的值是列表时,如何检查字典的任何元素中是否存在值?
问题描述
我有一个字典,它的值是一个列表,例如A = {'a':[1,2,3], 'b':[4,5,6], 'c':[7,8,9]}
,我想检查该值是否2
存在于字典的值中。因为A.values()
将返回一个列表,每个元素都是一个列表,所以这样做2 in A.values()
总是会返回 false。是否可以在不遍历每个值的情况下解决这个问题?
解决方案
You'll have to loop some way, either yourself or with built-in functionality. Here's an explicit loop over the values and a "hidden" loop using in
.
any(2 in v for v in A.values())
Note this only goes as far as necessary, stops the search as soon as it finds the value. And only takes O(1) space.
推荐阅读
- python - 当我注销或注册“7z”压缩扩展时,Python 代码生成 ValueError 和 Registry 错误
- sql - 每个月从每个卖家中选择第一个买家
- reactjs - 基于自动完成值 React js - Material Ui 禁用文本字段
- sql-server - 执行存储过程时列名无效
- google-meet - Google Meet 自动静音计时器
- javascript - 在底部选项卡屏幕之间导航时更改标题文本
- python-3.x - statsmodels acf plot 和 pacf plot 中的滞后数问题
- r - 追加(向量/列表)的时间复杂度是多少?
- php - LexikFormFilterBundle 从关系中丢失条件
- c# - 将扩展方法转换为自定义 DisplayFormatAttribute