繁体   English   中英

如何检查列表是否包含在 python 中字典的任何键中?

[英]How to check if a list is contained within any of the keys of a dictionary in python?

大家好,例如,我正在尝试检查列表的所有元素是否包含在字典的任何键中,只要它们位于同一键上;

dict = {1:{1,2,3,4,5,6},2:{10,2,9,8,5,7},3:{11,9,3,13},4:{12,8,4,13,14},}

我有这 3 个清单

[1,2,9],[2,9,8],[9,8,12]

只有第二个列表应该返回 true,因为它的值包含在字典的键 2 中,其他列表都应该返回 false

有人可以帮助找到一种方法吗?

您可以将嵌套列表推导与any和集合操作一起使用。

d = {1:{1,2,3,4,5,6},2:{10,2,9,8,5,7},3:{11,9,3,13},4:{12,8,4,13,14},}

to_check = [1,2,9],[2,9,8],[9,8,12]

res = [any(j.issuperset(i) for j in d.values()) for i in to_check]

Output

[False, True, False]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM