栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

测试字典中是否包含字典

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

测试字典中是否包含字典

您可以使用字典视图:

# Python 2if first.viewitems() <= second.viewitems():    # true only if `first` is a subset of `second`# Python 3if first.items() <= second.items():    # true only if `first` is a subset of `second`

字典视图是Python 3中的标准,在Python
2中,您需要在标准方法前加上

view
。它们的作用类似于集合,并
<=
测试其中一个是否是另一个的子集(或等于另一个)的子集。

Python 3演示:

>>> first  = {"one":"un", "two":"deux", "three":"trois"}>>> second = {"one":"un", "two":"deux", "three":"trois", "foo":"bar"}>>> first.items() <= second.items()True>>> first['four'] =  'quatre'>>> first.items() <= second.items()False

这也适用于 不可散列的值 ,因为键已经使键值对唯一。关于这一点,文档有点令人困惑,但是即使使用可变值(例如,列表),该方法也可以工作:

>>> first_mutable = {'one': ['un', 'een', 'einz'], 'two': ['deux', 'twee', 'zwei']}>>> second_mutable = {'one': ['un', 'een', 'einz'], 'two': ['deux', 'twee', 'zwei'], 'three': ['trois', 'drie', 'drei']}>>> first_mutable.items() <= second_mutable.items()True>>> first_mutable['one'].append('ichi')>>> first_mutable.items() <= second_mutable.items()False

您还可以将

all()
函数与生成器表达式一起使用;使用
object()
定为定点检测简明缺失值:

sentinel = object()if all(first[key] == second.get(key, sentinel) for key in first):    # true only if `first` is a subset of `second`

但这不像使用字典视图那样可读性和表达力强。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/611847.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号