我是靠谱客的博主 炙热枫叶,这篇文章主要介绍python断言测试—使用列表推导式(List Comprehensions)来检查列表(list)或字典(dict)中是否包含指定项目,现在分享给大家,希望可以做个参考。
Dict字典:
原代码:
name = 'TmlMYzapFP'
search_result =
[{'name': 'pnaXSsHBsf', 'interval': 60, 'debug': True, 'id': 102},
{'name': 'PidFUZfXzx', 'interval': 60, 'debug': True, 'id': 146},
{'name': 'TmlMYzapFP', 'interval': 60, 'debug': True, 'id': 147}]
assert_flag = None #标志位|flag
for item in search_result:
if item['name'] == name:
assert_flag = True
break
assert assert_flag == True #找到后退出循环|find it and then exit loop
It’s more pythonic to use list comprehension and check if returned list has any items:
可以使用列表推导式(List Comprehensions)来检查list或dict中是否包含指定项目,这样的写法高效且简短:
优化后代码:
name = 'TmlMYzapFP'
search_result =
[{'name': 'pnaXSsHBsf', 'interval': 60, 'debug': True, 'id': 102},
{'name': 'PidFUZfXzx', 'interval': 60, 'debug': True, 'id': 146},
{'name': 'TmlMYzapFP', 'interval': 60, 'debug': True, 'id': 147}]
assert [item for item in search_result if item['name'] == name]
由上对比,使用列表推导式简略了多行代码,整体代码风格更加优雅。
最后
以上就是炙热枫叶最近收集整理的关于python断言测试—使用列表推导式(List Comprehensions)来检查列表(list)或字典(dict)中是否包含指定项目的全部内容,更多相关python断言测试—使用列表推导式(List内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复