首页 > 解决方案 > python:当字典的值是列表时,如何检查字典的任何元素中是否存在值?

问题描述

我有一个字典,它的值是一个列表,例如A = {'a':[1,2,3], 'b':[4,5,6], 'c':[7,8,9]},我想检查该值是否2存在于字典的值中。因为A.values()将返回一个列表,每个元素都是一个列表,所以这样做2 in A.values()总是会返回 false。是否可以在不遍历每个值的情况下解决这个问题?

标签: python

解决方案


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.


推荐阅读